CREATE procedure DBO.GetTotalCheckFolio @FolioNumber INT, @PkInvoice INT AS
SET NOCOUNT ON
/*
--nb20181010 Created
*/
DECLARE @Total MONEY, @Hcn INT
IF ISNULL(@PkInvoice, 0) < 0 
  SET @PkInvoice = 0
SELECT @Total = dbo.GetTotalFrontLegFolio(@FolioNumber, @PkInvoice)
IF @Total IS NULL AND ISNULL(@PkInvoice, 0) > 0  --someone could write Bill or Invoice value instead of PkInvoice
BEGIN
  /*
  SELECT @Hcn = HotelCustomerNumber FROM Folios (NOLOCK) WHERE FolioNumber= @FolioNumber
  SELECT @PkInvoice = PkInvoice FROM Invoice (NOLOCK) WHERE BillNumber = @PkInvoice AND FkCustomerHotel = @Hcn
  SELECT @Total = dbo.GetTotalFrontLegFolio(@FolioNumber, @PkInvoice)
  IF @Total IS NULL
  BEGIN
    SELECT @PkInvoice = PkInvoice FROM Invoice (NOLOCK) WHERE InvoiceNumber = @PkInvoice AND FkCustomerHotel = @Hcn
    SELECT @Total = dbo.GetTotalFrontLegFolio(@FolioNumber, @PkInvoice)
  END
  */
  DECLARE @PkFolio INT
  SELECT TOP 1 @PkFolio = FolioNumber FROM dbo.Transactions T (NOLOCK)
    JOIN dbo.InvoiceTransactionXTab ITX (NOLOCK) ON ITX.FkTransaction = T.TransactionNumber
  WHERE ITX.FkInvoice = @PkInvoice
  IF @FolioNumber <> @PkFolio --attempt only if PkInvoice does not belong to Folio (Total can also be valid = NULL)
  BEGIN
    SELECT @Hcn = HotelCustomerNumber FROM Folios (NOLOCK) WHERE FolioNumber= @FolioNumber
    SELECT @PkInvoice = PkInvoice FROM Invoice (NOLOCK) WHERE BillNumber = @PkInvoice AND FkCustomerHotel = @Hcn
    SELECT @Total = dbo.GetTotalFrontLegFolio(@FolioNumber, @PkInvoice)
    IF @Total IS NULL
    BEGIN
      SELECT @PkInvoice = PkInvoice FROM Invoice (NOLOCK) WHERE InvoiceNumber = @PkInvoice AND FkCustomerHotel = @Hcn
      SELECT @Total = dbo.GetTotalFrontLegFolio(@FolioNumber, @PkInvoice)
	  END
  END
END
SELECT Price AS XTax, Tax, ISNULL(Price, 0) + ISNULL(Tax, 0) AS Behind, @Total AS Front FROM GetBalanceReceipt(@FolioNumber, @PkInvoice)