Create  PROCEDURE [dbo].[GetSummaryFactors]
    @StartDate VARCHAR(10) ,
    @EndDate VARCHAR(10)
AS
    DECLARE @SD SMALLDATETIME ,
        @ED SMALLDATETIME ,
        @StoreCode VARCHAR(3);

    SET @SD = dbo.ShamsiToMiladi(@StartDate);
    SET @ED = dbo.ShamsiToMiladi(@EndDate);
    
    SELECT  @StoreCode = Code
    FROM    dbo.Shops
    WHERE   IsDefault = 0;

    SET @StartDate = ISNULL(@StartDate, '100');

    SELECT  dbo.MiladiToShamsi(Fact.FactorDate) FactorDate ,
            FD.GoodCode ,
            Good.Name1 GoodName ,
            Fact.Kind ,
            FD.WarehouseCode ,
            Fact.PersonCode ,
            PS.Name PSName ,
            U1.Name UName ,
            FD.GoodQty1 ,
            SalesPrice = CASE WHEN Fact.Kind IN ( 4, 5, 7, 8, 9, 1, 10, 11 )
                              THEN FD.SalesPrice
                              ELSE 0
                         END ,
            PurchasePrice = CASE WHEN Fact.Kind IN ( 0, 2, 3, 6, 1, 10, 11 )
                                 THEN FD.PurchasePrice
                                 ELSE 0
                            END ,
            TotalPrice = FD.GoodQty1
            * ( CASE WHEN Fact.Kind IN ( 0, 2, 3, 6 ) THEN FD.PurchasePrice
                     WHEN Fact.Kind IN ( 4, 5, 7, 8, 9 ) THEN FD.SalesPrice
                END ) ,
            CASE WHEN FD.IsCooperative = 0 THEN 'نقدي'
                 ELSE 'مشارکتي'
            END Coopreative ,
            KindName = CASE WHEN Fact.Kind = 0 THEN 'برگشت از عمده فروشي'
                            WHEN Fact.Kind = 1 THEN 'نقل و انتقال بين انباري'
                            WHEN Fact.Kind = 2 THEN 'رسيد افتتاحيه'
                            WHEN Fact.Kind = 3 THEN 'خـريد'
                            WHEN Fact.Kind = 4 THEN 'برگشت از خريد'
                            WHEN Fact.Kind = 5 THEN 'فـروش'
                            WHEN Fact.Kind = 6 THEN 'برگشت از فروش'
                            WHEN Fact.Kind = 7 THEN 'خرده فروشي'
                            WHEN Fact.Kind = 8 THEN 'برگشت از خرده فروشي'
                            WHEN Fact.Kind = 9 THEN 'عمده فروشي'
                            WHEN Fact.Kind = 10 THEN 'حواله به شعب'
                            WHEN Fact.Kind = 11 THEN 'رسيد از شعب'
                       END ,
            Fact.StoreCode
    FROM    dbo.SummaryFactors Fact
            LEFT JOIN dbo.Guy PS ON PS.Guy_Code = PersonCode
            JOIN dbo.SummaryFactorDetails FD ON FD.FactorId = Fact.Id
            LEFT JOIN dbo.KalaId Good ON Good.K_Code = GoodCode
            LEFT JOIN dbo.Unit1 U1 ON U1.U_Code1 = Good.U_Code1
    WHERE   Fact.FactorDate BETWEEN @SD AND @ED
    ORDER BY Good.Name1;




