Create  PROC [dbo].[CreateSummaryFactors]
    @InputStartDate VARCHAR(10) = NULL ,
	@InputEndDate  VARCHAR(10) = NULL ,
    @InputFactorKind TINYINT = NULL
AS
    DECLARE @FactorDate SMALLDATETIME;    
    DECLARE @Flag TINYINT;
    DECLARE @PersonCode VARCHAR(5);
    DECLARE @StoreCode VARCHAR(3);
    DECLARE @CurrentId UNIQUEIDENTIFIER;	
	DECLARE @StartDate SMALLDATETIME  = dbo.ShamsiToMiladi(@InputStartDate)
	DECLARE @EndDate SMALLDATETIME  = dbo.ShamsiToMiladi(@InputEndDate)

    SET @InputFactorKind = CASE WHEN @InputFactorKind = 10 THEN 1
                                ELSE @InputFactorKind
                           END;
    DECLARE @Factor TABLE
        (
          Id BIGINT ,
          Flag TINYINT ,
          PersonCode VARCHAR(5) ,
          FactorDate SMALLDATETIME
        );
    DECLARE @FactorDetail TABLE
        (
          FactorId BIGINT ,
          Id BIGINT ,
          GoodCode VARCHAR(15) ,
          WarehouseCode VARCHAR(3) ,
          GoodQty1 MONEY ,
          GoodQty2 MONEY ,
          UnitRelation REAL ,
          PurchasePrice MONEY ,
          MajorPrice MONEY ,
          SalesPrice MONEY ,
          ConsumerPrice MONEY ,
          IsCooperative BIT ,
          IsIncludesTax BIT ,
          IsDecimal BIT ,
          ChainFlag BIT
        );

    SELECT  @StoreCode = ISNULL(Code, '100')
    FROM    dbo.Shops
    WHERE   IsDefault = 1;

    INSERT  INTO @Factor
            ( Id ,
              Flag ,
              PersonCode ,
              FactorDate 
            )
            SELECT  headH.Id_Havaleh ,
                    Kind = CASE WHEN Kind_Flag = 1
                                     AND Nu_Bargasht_Forosh = 'chain' THEN 10
                                WHEN Kind_Flag = 1
                                     AND Nu_Bargasht_Forosh <> 'chain' THEN 1
                                ELSE Kind_Flag
                           END ,
                    PersonCode = CASE WHEN Kind_Flag IN ( 0, 1, 2, 3, 6, 8 )
                                           AND ISNULL(Nu_Bargasht_Forosh, '') <> 'chain'
                                      THEN Sender
                                      WHEN Kind_Flag IN ( 4, 5, 7, 9 )
                                      THEN Reciver
                                      WHEN Kind_Flag = 1
                                           AND Nu_Bargasht_Forosh = 'chain'
                                      THEN Reciver
                                 END ,
                    Tarikh_faktor
            FROM    dbo.headH WITH ( NOLOCK )
                    JOIN dbo.Havaleh WITH ( NOLOCK ) ON Havaleh.Id_Havaleh = headH.Id_Havaleh
                                                        AND ISNULL(Havaleh.ChainFlag,0) = 0
            WHERE   dbo.headH.Tarikh_Faktor BETWEEN ISNULL(@StartDate,headH.Tarikh_faktor) AND ISNULL(@EndDate ,headH.Tarikh_faktor)
                    AND Kind_Flag = ISNULL(@InputFactorKind, Kind_Flag)
            GROUP BY headH.Id_Havaleh ,
                    Nu_Bargasht_Forosh ,
                    Tarikh_faktor ,
                    Kind_Flag ,
                    CASE WHEN Kind_Flag IN ( 0, 1, 2, 3, 6, 8 )
                              AND ISNULL(Nu_Bargasht_Forosh, '') <> 'chain'
                         THEN Sender
                         WHEN Kind_Flag IN ( 4, 5, 7, 9 ) THEN Reciver
                         WHEN Kind_Flag = 1
                              AND Nu_Bargasht_Forosh = 'chain' THEN Reciver
                    END;
    PRINT 'INSERT  INTO @Factor';
    --SELECT  *
    --FROM    @Factor;
-----------------------------------------------------------------------------
    BEGIN TRY
        BEGIN TRANSACTION; 
        DECLARE factorCursor CURSOR
        FOR
            SELECT  FactorDate ,
                    Flag ,
                    PersonCode
            FROM    @Factor
                --INNER JOIN Guy WITH ( NOLOCK ) ON Guy.Guy_Code = PersonCode
            GROUP BY FactorDate ,
                    Flag ,
                    PersonCode
            ORDER BY FactorDate;

        OPEN factorCursor;
        FETCH NEXT FROM factorCursor INTO @FactorDate, @Flag, @PersonCode;
        WHILE @@FETCH_STATUS = 0
            BEGIN
	   
                INSERT  INTO @FactorDetail
                        ( FactorId ,
                          Id ,
                          GoodCode ,
                          WarehouseCode ,
                          GoodQty1 ,
                          GoodQty2 ,
                          UnitRelation ,
                          PurchasePrice ,
                          MajorPrice ,
                          SalesPrice ,
                          ConsumerPrice ,
                          IsCooperative ,
                          IsIncludesTax ,
                          IsDecimal ,
                          ChainFlag
                        )
                        SELECT  Id_Havaleh ,
                                AutoId ,
                                K_Code ,
                                CASE WHEN Flag IN ( 0, 1, 2, 3, 6, 8 )
                                     THEN Reciver
                                     WHEN Flag IN ( 4, 5, 7, 9, 10 )
                                     THEN Sender
                                END ,
                                K_Qty1 ,
                                K_Qty2 ,
                                R_Unit1_2 ,
                                ISNULL(Price_KHarid, 0) ,
                                ISNULL(Price_Omdeh, 0) ,
                                ISNULL(Price_Forosh, 0) ,
                                ISNULL(Price_Consumer, 0) ,
                                ISNULL(Cooperative_Flag, 0) ,
                                ISNULL(Takhfif_flag, 0) ,
                                ISNULL(Point_Flag, 0) ,
                                ISNULL(ChainFlag, 0)
                        FROM    Havaleh
                                JOIN @Factor ON [@Factor].Id = Havaleh.Id_Havaleh
                                                AND [@Factor].PersonCode = @PersonCode
                        WHERE   [@Factor].FactorDate = @FactorDate
                                AND ISNULL(Havaleh.ChainFlag, 0) = 0
                                AND [@Factor].PersonCode = CASE
                                                              WHEN Flag IN ( 0,
                                                              2, 3, 6, 8, 1 )
                                                              THEN Sender
                                                              WHEN Flag IN ( 4,
                                                              5, 7, 9, 10 )
                                                              THEN Reciver
                                                           END
                                AND [@Factor].Flag = @Flag;
        
                PRINT 'INSERT  INTO @FactorDetail';   
-----------------------------------------------------------------------------
                IF NOT EXISTS ( SELECT  PersonCode
                                FROM    dbo.SummaryFactors
                                WHERE   FactorDate = @FactorDate
                                        AND Kind = @Flag AND @Flag <> 10
                                        AND PersonCode = @PersonCode )
                    BEGIN
                        SET @CurrentId = NEWID();
                        PRINT @CurrentId;
                        INSERT  INTO dbo.SummaryFactors
                                ( Id ,
                                  Kind ,
                                  PersonCode ,
                                  FactorDate ,
                                  StoreCode 
	                            )
                        VALUES  ( @CurrentId ,
                                  @Flag ,
                                  @PersonCode ,
                                  @FactorDate ,
                                  @StoreCode
                                );  
                        PRINT 'INSERT  INTO dbo.SummaryFactors';				             
------------------------------------------------------------------------------
                        INSERT  INTO dbo.SummaryFactorDetails
                                ( FactorId ,
                                  GoodCode ,
                                  WarehouseCode ,
                                  GoodQty1 ,
                                  GoodQty2 ,
                                  UnitRelation ,
                                  PurchasePrice ,
                                  MajorPrice ,
                                  SalesPrice ,
                                  ConsumerPrice ,
                                  IsCooperative ,
                                  IsIncludesTax ,
                                  IsDecimal
                                )
                                SELECT  @CurrentId ,
                                        GoodCode ,
                                        WarehouseCode ,
                                        SUM(GoodQty1) ,
                                        SUM(GoodQty2) ,
                                        UnitRelation ,
                                        PurchasePrice ,
                                        MajorPrice ,
                                        SalesPrice ,
                                        ConsumerPrice ,
                                        IsCooperative ,
                                        IsIncludesTax ,
                                        IsDecimal
                                FROM    @FactorDetail
                                        JOIN @Factor ON [@Factor].Id = [@FactorDetail].FactorId
                                WHERE   [@Factor].FactorDate = @FactorDate
                                        AND [@Factor].Flag = @Flag
                                        AND [@Factor].PersonCode = @PersonCode
                                GROUP BY GoodCode ,
                                        WarehouseCode ,
                                        PersonCode ,
                                        Flag ,
                                        UnitRelation ,
                                        PurchasePrice ,
                                        MajorPrice ,
                                        SalesPrice ,
                                        ConsumerPrice ,
                                        IsCooperative ,
                                        IsIncludesTax ,
                                        IsDecimal;     
                    
                        PRINT 'INSERT  INTO dbo.SummaryFactorDetails';	         
                    END;
                ELSE
                    BEGIN
                        SELECT  @CurrentId = Id
                        FROM    dbo.SummaryFactors
                        WHERE   Kind = @Flag
                                AND PersonCode = @PersonCode
                                AND FactorDate = @FactorDate;

                        UPDATE  dbo.SummaryFactorDetails
                        SET     GoodQty1 = GoodQty1 + fd.SumQty1 ,
                                GoodQty2 = GoodQty2 + fd.SumQty2
                        FROM    SummaryFactorDetails
                                JOIN ( SELECT   @CurrentId factId ,
                                                GoodCode ,
                                                WarehouseCode ,
                                                SUM(GoodQty1) SumQty1 ,
                                                SUM(GoodQty2) SumQty2 ,
                                                UnitRelation ,
                                                PurchasePrice ,
                                                MajorPrice ,
                                                SalesPrice ,
                                                ConsumerPrice ,
                                                IsCooperative ,
                                                IsIncludesTax ,
                                                IsDecimal
                                       FROM     @FactorDetail
                                                JOIN @Factor ON [@Factor].Id = [@FactorDetail].FactorId
                                       WHERE    [@FactorDetail].ChainFlag = 0
                                                AND [@Factor].PersonCode = @PersonCode
                                                AND [@Factor].Flag = @Flag
                                                AND [@Factor].FactorDate = @FactorDate
                                       GROUP BY GoodCode ,
                                                WarehouseCode ,
                                                PersonCode ,
                                                Flag ,
                                                UnitRelation ,
                                                PurchasePrice ,
                                                MajorPrice ,
                                                SalesPrice ,
                                                ConsumerPrice ,
                                                IsCooperative ,
                                                IsIncludesTax ,
                                                IsDecimal
                                     ) AS fd ON fd.factId = dbo.SummaryFactorDetails.FactorId
                                                AND fd.GoodCode = SummaryFactorDetails.GoodCode
                                                AND fd.IsDecimal = SummaryFactorDetails.IsDecimal
                                                AND fd.ConsumerPrice = SummaryFactorDetails.ConsumerPrice
                                                AND fd.SalesPrice = SummaryFactorDetails.SalesPrice
                                                AND fd.PurchasePrice = SummaryFactorDetails.PurchasePrice
                                                AND fd.MajorPrice = SummaryFactorDetails.MajorPrice
                                                AND fd.UnitRelation = SummaryFactorDetails.UnitRelation
                                                AND fd.IsIncludesTax = SummaryFactorDetails.IsIncludesTax
                                                AND fd.WarehouseCode = SummaryFactorDetails.WarehouseCode;

                        PRINT 'Update SummaryFactorDetails';
--------------------------------------------------------------------------------------------------
                        UPDATE  Havaleh
                        SET     ChainFlag = 1
                        FROM    Havaleh
                                JOIN ( SELECT   IsDecimal ,
                                                ConsumerPrice ,
                                                SalesPrice ,
                                                PurchasePrice ,
                                                MajorPrice ,
                                                UnitRelation ,
                                                IsIncludesTax ,
                                                WarehouseCode ,
                                                GoodCode ,
                                                PersonCode
                                       FROM     dbo.SummaryFactorDetails
                                                JOIN dbo.SummaryFactors ON SummaryFactors.Id = dbo.SummaryFactorDetails.FactorId
                                       WHERE    FactorDate = @FactorDate
                                                AND PersonCode = @PersonCode
                                                AND Kind = @Flag
                                     ) AS fd ON fd.GoodCode = Havaleh.K_Code
                                                AND fd.IsDecimal = ISNULL(Havaleh.Point_Flag,0)
                                                AND fd.ConsumerPrice = Havaleh.Price_Consumer
                                                AND fd.SalesPrice = Havaleh.Price_Forosh
                                                AND fd.PurchasePrice = Havaleh.Price_KHarid
                                                AND fd.MajorPrice = Havaleh.Price_Omdeh
                                                AND fd.UnitRelation = Havaleh.R_Unit1_2
                                                AND fd.IsIncludesTax = ISNULL(Havaleh.Takhfif_flag , 0) 
                                                AND fd.WarehouseCode = CASE
                                                              WHEN @Flag IN (
                                                              0, 2, 3, 6, 8, 1 )
                                                              THEN Reciver
                                                              WHEN @Flag IN (
                                                              4, 5, 7, 9, 10 )
                                                              THEN Sender
                                                              END
                                                AND fd.PersonCode = @PersonCode
                        WHERE   ChainFlag = 0; 
    --------------------------------------------------
                        UPDATE  @FactorDetail
                        SET     ChainFlag = 1
                        FROM    @FactorDetail
                                JOIN dbo.Havaleh ON dbo.Havaleh.AutoId = [@FactorDetail].Id
                        WHERE   Havaleh.ChainFlag = 1
                                AND ISNULL([@FactorDetail].ChainFlag, 0) = 0;		
------------------------------------------------------------------------------------------------
                        INSERT  INTO dbo.SummaryFactorDetails
                                ( FactorId ,
                                  GoodCode ,
                                  WarehouseCode ,
                                  GoodQty1 ,
                                  GoodQty2 ,
                                  UnitRelation ,
                                  PurchasePrice ,
                                  MajorPrice ,
                                  SalesPrice ,
                                  ConsumerPrice ,
                                  IsCooperative ,
                                  IsIncludesTax ,
                                  IsDecimal
                                )
                                SELECT  @CurrentId ,
                                        GoodCode ,
                                        WarehouseCode ,
                                        SUM(GoodQty1) ,
                                        SUM(GoodQty2) ,
                                        UnitRelation ,
                                        PurchasePrice ,
                                        MajorPrice ,
                                        SalesPrice ,
                                        ConsumerPrice ,
                                        IsCooperative ,
                                        IsIncludesTax ,
                                        IsDecimal
                                FROM    @FactorDetail
                                        JOIN @Factor ON [@Factor].Id = [@FactorDetail].FactorId
                                WHERE   ISNULL(ChainFlag, 0) = 0
                                        AND [@Factor].PersonCode = @PersonCode
                                        AND [@Factor].Flag = @Flag
                                        AND [@Factor].FactorDate = @FactorDate
                                GROUP BY GoodCode ,
                                        WarehouseCode ,
                                        PersonCode ,
                                        Flag ,
                                        UnitRelation ,
                                        PurchasePrice ,
                                        MajorPrice ,
                                        SalesPrice ,
                                        ConsumerPrice ,
                                        IsCooperative ,
                                        IsIncludesTax ,
                                        IsDecimal;		
                        PRINT 'INSERT  INTO dbo.SummaryFactorDetails';

                    END;                        
                FETCH NEXT FROM factorCursor INTO @FactorDate, @Flag,
                    @PersonCode;
            END;
        CLOSE factorCursor;
        DEALLOCATE factorCursor; 
----------------------------------------------------------------------------------------------------
        UPDATE  dbo.Havaleh
        SET     ChainFlag = 1
        WHERE   Id_Havaleh IN ( SELECT  Id
                                FROM    @Factor );
----------------------------------------------------------------------------------------------------
        COMMIT TRAN;
    END TRY 
    BEGIN CATCH
        PRINT ERROR_MESSAGE()
		PRINT ERROR_STATE()
		DECLARE @ErrorMessage NVARCHAR(MAX) ,
            @ErrorSeverity INT ,
            @ErrorState INT;
        SELECT  @ErrorMessage = ERROR_MESSAGE() + ' Line '
                + CAST(ERROR_LINE() AS NVARCHAR(5)) ,
                @ErrorSeverity = ERROR_SEVERITY() ,
                @ErrorState = ERROR_STATE();
        ROLLBACK TRANSACTION;
        RAISERROR (@ErrorMessage, @ErrorSeverity, @ErrorState);
    END CATCH;

