CREATE PROCEDURE dbo.CheckoutReservationFolios @ReferenceNumber INT, @GuestNumber INT, @FkUser INT = NULL, @FkDepartment INT = NULL, @IdentityKind INT = 1 AS
SET NOCOUNT ON
/*
nb20241119 New  
Comments:
Checkout balanced folios, make receipt if necessary
*/
DECLARE @DebugLevel TINYINT
SET @DebugLevel = 0
IF @DebugLevel >= 1 
BEGIN
  PRINT '---- CheckoutReservationFolios Pre ---'
END

DECLARE @FkFolio INT, @PkInvoice INT
DECLARE #FolioCur CURSOR FAST_FORWARD READ_ONLY FOR
SELECT FolioNumber FROM dbo.Folios F (NOLOCK) 
  LEFT JOIN dbo.ReservationAddress RA (NOLOCK) ON RA.AddressNumber = F.ReservationAddressNumber
WHERE F.ReferenceNumber = @ReferenceNumber AND F.GuestNumber = @GuestNumber
ORDER BY RA.AddressType
OPEN #FolioCur
FETCH NEXT FROM #FolioCur
INTO @FkFolio
WHILE @@FETCH_STATUS = 0 -- safe
BEGIN
  exec dbo.CreateReceipt @PkInvoice OUTPUT, @FkFolio, @FkUser, @FkDepartment, @IdentityKind
  IF @DebugLevel >= 1 
  BEGIN
    PRINT '@PkInvoice = ' + CONVERT(NVARCHAR, ISNULL(@PkInvoice, 0))
  END
  IF @PkInvoice >= 0
    UPDATE Folios SET OpenFolio = 0 WHERE FolioNumber = @FkFolio
  FETCH NEXT FROM #FolioCur
  INTO @FkFolio
END
CLOSE #FolioCur
DEALLOCATE #FolioCur

