SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[sp_RegisterFactRecalcInfo]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_RegisterFactRecalcInfo]
GO
-- =============================================
-- Author:      Vitacore (с)
-- Create date: 2021-02-06
-- Description: Регистрация информации о наличии изменений в расчёте факта после открытия или закрытия расчёта
-- =============================================
CREATE PROCEDURE [dbo].[sp_RegisterFactRecalcInfo]
  @setting uniqueidentifier,
  @ids xml
AS
BEGIN

    select T.c.value('.', 'uniqueidentifier') as id
        into #ids
    from @ids.nodes('/ids/id') T(c)

    select fs.PeriodValue as MonthNumber
            into #ms
    from IES.T_FACT_CALC_SETTING fs
    where fs.FactCalcSettingID = @setting and fs.IsClosed = 1 and fs.PeriodValue < 13
    union all
    select m.MonthNumber
    from IES.T_FACT_CALC_SETTING fs,
            (
                    select 13 QuarterNumber, 1 MonthNumber
                    union all select 13, 2
                    union all select 13, 3
                    union all select 14, 4
                    union all select 14, 5
                    union all select 14, 6
                    union all select 15, 7
                    union all select 15, 8
                    union all select 15, 9
                    union all select 16, 10
                    union all select 16, 11
                    union all select 16, 12
            ) m
    where fs.FactCalcSettingID = @setting and fs.IsClosed = 1 and fs.PeriodValue = m.QuarterNumber

    INSERT INTO [IES].[T_FACT_RECALC_INFO]
               ([FactRecalcInfoID] ,[FactCalcSetting] ,[SchetID])
    select NEWID(), @setting, s.SchetID
    from IES.T_SCHET s
        join #ids i on i.id = s.SchetID
        join #ms m on m.MonthNumber = s.[MONTH]
    where not exists
        (
            select *
            from IES.T_PLAN_CUT_DICTIONARY pcd 
            where pcd.FactCalcSetting = @setting
        )
            and
        not exists
        (
            select *
            from IES.T_FACT_RECALC_INFO ri
            where ri.FactCalcSetting = @setting
                    and
                ri.SchetID = s.SchetID
        )

    drop table #ids;
    drop table #ms
END
GO
