CREATE PROCEDURE [dbo].[Sp_Office_FactorPayable] @Id BIGINT AS
              
SELECT TotForosh + ISNULL(DifferOu,0) + ISNULL(Cash.SumCheqe,0) Payable 
FROM (
       SELECT Id_Havaleh, Tot_Price_forosh TotForosh FROM  headH
       WHERE Id_Havaleh = @Id
     ) AS Factor
LEFT OUTER JOIN (
                  SELECT Id_Havaleh, 
                  SUM(CASE WHEN Type = 1 THEN Price ELSE 0 END)- SUM(CASE WHEN Type = 0 THEN Price ELSE 0 END) DifferOu
                  FROM Over_Under_Factor 
                  WHERE Id_Havaleh = @Id
                  GROUP BY Id_Havaleh
                ) AS OverUnder ON Factor.Id_Havaleh = OverUnder.Id_Havaleh
LEFT OUTER JOIN (
                  SELECT Id_Havaleh, -SUM(Ch_Price) SumCheqe  FROM dbo.HeadC
                  INNER JOIN dbo.Cheqe ON Cheqe.Id_Cheqe = Headc.Id_Cheqe
                  WHERE Id_Havaleh =  @Id
                  GROUP BY Id_Havaleh, Kind_Flag
                 ) AS Cash ON Cash.Id_Havaleh = Factor.Id_Havaleh
