CREATE PROCEDURE  [dbo].[Sp_Duty_Row]  @IdHavaleh Bigint , @AutoId numeric(18, 0), @ActionCode tinyint
AS
 IF (Select Count(Price_Row) Icount From Tmp_Over_Under_Row WITH (NOLOCK)
     WHERE Price_Row = 1 And ShowPrice = 1 And AutoId  = @AutoId) > 0 
 Begin

DECLARE @TotPrice Money
SELECT @Totprice =  ISNULL(T2.SumRow,0)  - Abs(TotOverUnder)  
FROM (
       SELECT Tmp_Over_Under_Row.Autoid, 
       (SUM(CASE WHEN dbo.Tmp_Over_Under_Row.Type = 1 THEN price ELSE 0 END) - SUM(CASE WHEN Tmp_Over_Under_Row.Type = 0 THEN price ELSE 0 END)) TotOverUnder
       FROM dbo.Tmp_Over_Under_Row WITH (NOLOCK)
       INNER JOIN dbo.Over_Under WITH (NOLOCK) ON OVER_Under.AutoId = Code_Over_Under
       WHERE dbo.Tmp_Over_Under_Row.Autoid = @AutoId
       AND dbo.Over_Under.Duty_Flag = 1
       AND Action_Code = @ActionCode 
       GROUP BY Tmp_Over_Under_Row.AutoId
     ) AS T1
Inner Join(
		     Select TmpHeadH.Id_Havaleh, AutoId,
		     Case
		       When Kind_Flag in (5,9,7,0,6) THEN Round(K_Qty1 * Price_Forosh,0)
		       When Kind_Flag in (2,3,4,8)   THEN Round(K_Qty1 * Price_Kharid,0)
		     End As SumRow
		     From TmpHeadH WITH (NOLOCK) INNER Join TmpHavaleh WITH (NOLOCK) ON TmpHavaleh.Id_Havaleh = TmpHeadH.Id_Havaleh
		     Where dbo.TmpHavaleh.Autoid = @AutoId AND Takhfif_Flag = 1
           ) As T2 
            On T1.AutoId = T2.AutoId

  
  IF ISNULL(@TotPrice,0) > 0 
  Begin
	  UPDATE dbo.Tmp_Over_Under_Row SET price =ROUND(@TotPrice * [percent]/100,0) FROM Tmp_Over_Under_Row WITH (NOLOCK)
      INNER JOIN dbo.Over_Under WITH (NOLOCK) ON over_under.AutoId = Code_Over_Under 
	  INNER JOIN Tmphavaleh WITH (NOLOCK) ON Tmphavaleh.AutoId = Tmp_Over_Under_Row.Autoid
	  Where Price_Row = 1 And Tmp_Over_Under_Row.ShowPrice = 1  AND TmpHavaleh.Autoid = @AutoId
  END
End

