CREATE PROCEDURE [dbo].[OnlinePostering]  @Referencenumber INT, @WareTextOverwrite VARCHAR(150), @TotalPrice MONEY, @Note VARCHAR(50) , @TransNrShowOnBill INT OUTPUT, 
  @AGlobalTransactionNumber INT = 0, @AGuestNumber INT = 0, @AOverwriteCheckForMultipleTransactions BIT = 0, @ACreditCardFee MONEY = 0, @AUserId INT = 0, 
  @AWareNumber INT = 0, @AWareNumberInhouse INT = 0, @AOnlineCCType VARCHAR(100) = '', @DepositFollowupNumber INT = -1, 
  @AOnlinePaymentId VARCHAR(100) = '', @AOnlineTransactionId VARCHAR(100) = '', @AInvoiceFee MONEY = 0, @ASetResGuaranteed BIT = 0 AS
SET NOCOUNT ON

/*
  Created by Troels Buch Marts 2005
    
  Changes:
  KJ 20250210: Bug: Fix for "The INSERT statement conflicted with the FOREIGN KEY constraint "FK_TransactionOnlinePaymentXtab_OnlinePayment".table "dbo.OnlinePayment", column 'Id'. Line 406".
  KJ 20240201: Change reservation status when paid online based on reservation total amount
  KJ 20220726: Errortext updated.
  MLJ 2022-03-25: Now checks HotelSetup_DefaultValues for userid if not found in HotelSetup
  KJ 20220315: Added @AInvoiceFee
  MLJ 2022-03-11: 'This SP is called multiple times' is not raised when called from OTA. Instead Sp just returns.
  KJ 20200904: Ext: Added Payment and TransationId for use with OnlinePaymentModule
  KJ 20190528: Ext: Added try catch to break out of sp if any exception/error happens
  KJ 20170306: Bug: Fix for "@TransNrShowOnBill not set" 
  KJ 20161212: Bug: Fix for "Wrong payment ware is used to post. First use CC setup. if not setup then use from hotelsetup. if not deposit, then use first deposit payment ware".
  KJ 20161212: Bug: Fix for "Not able to post Credit card fee if depositfollowupnumber is set"
  KJ 20161129: Bug: Fix for "Error running without DepositFollowupNumber"
  KJ 20161116: Ext: Added post received deposit. Req #3209
  KJ 20160917: Bug: Fix for "Error caling postering if CashDesk is enabled". Case #CR112261
  KJ 20150611: Bug: Fix for "Wrong department for credit card fee extras"
  KJ 20150513: Bug: Fix for "Deleted wares is used".
  KJ 20150505: Bug: Fix for "Arrangement line for cc fee not saved correctly"
  KJ 20150413: Ext: Added post cc fee as arrangement
  KJ 20150316: Ext: Added OnlineCCType.
  KJ 20141013: Ext: Fit for use with BW OTA.
  KJ 20140611: Ext: CashDesk per hotel. Case #CR073269
  KJ 20121212: Ext: Added support for credit card fee.
  KJ 20111201: Bug: Fix for "Error when calling sp from PayAndCheckOut-app. (payment when inhouse)".
  KJ 20111014: Bug: Fix for "This sp updates the moveddelete stauts on old Transactions when called in online checkout". Case #CR034965
  KJ 20110624: Bug: Fix for "Online warenumber is per hotel".
  KJ 20110308: Bug: Fix for "Raise error when online ware entry is set to NONE"
  KJ 20110211: Bug: Fix for "Raise error when inhouse payment isn't set"
  KJ 20110131: Ext: Added support for GuestNumber > 0 and payment for inhouse reservations
  KJ 20101229: Bug: Fix for "CashBox not always set"
  NB 20101128: Bug: In Domino the wrong cashbox used because not relation to the hotel. Relation now added and Externals should specify internally the correct cashbox used for Online
  KJ 20100713: Bug: Fix for "wrong cashbox relation"
  KJ 20100211: Bug: Fix for "Wrong department for Domino Hotels"
  KJ 20081217: Ext: Added GlobalTransactionNumber as input param
  KJ 20081217: Bug: Fix for "Moved deleted on online deposit"
  KJ 20080103: Bug: Fix for "Do not raise error when other transactions than deposit has been made"
  KJ 20071018: Added Raise error when some deposit transactions is marked as deleted.
  KJ 20070620: Fix error for @Departments
  KJ 20070412: Department Rewrite
  KJ 20070306: Changed the way to check for sp called multiple times
  KJ 20070112: Fix for "Sometimes this SP is called multiple times."
  TB20060330: Removed begin tran
  KJ 20060215: Changed update transactions.
  KJ20060123: Possible fix for MovedDeleted = 1
  KJ20060119: Making sure that MovedDeleted = 0
  KJ20060116: Fix for "Not the correct HotelNumber in Followup-table"
  TB20051221: Check if If Domino before change Department
  TB20051220: Added check for Logstor - Must be changed as soon as Hotelsetup can handle Domino
  KJ20051123: Followup: Userid changed to Onlineuser, and not '!' as default
  KJ20051122: Added Update of DepositFollowupNumber
  KJ20051109: The DepositFollowNumber removed again.
  KJ20051104: Added DepositFollowupNumber to call to Postering SP
  KJ20051028: Removed @ErrorLevel -> not used.
  KJ20051028: Added RaiseError if @referencenumber <= 0
  KJ20050707: Forgot to set @CentralBookingType
  KJ20050706: Moved the line 'deallocate db_cur'
  KJ20050630: Only create followup if payment = 12 (recieved deposit)
  TB20050621: Now calling postering again
  KJ20050616: Creating followups. 
  TB/KJ20050616: Payment not set. Getting the payment type from ware.
  TB20050615: Changed @Department to VARCHAR insted of INT
  TB20050408: Changed check on @Department, @Warenumber and @CountryidCount from -1 to 0
*/

DECLARE @UserId INT
DECLARE @FK_Department INT
DECLARE @Warenumber INT
DECLARE @WareNumberInhouse INT
DECLARE @CentralBookingType smallint
DECLARE @Payment INT
DECLARE @PaymentInhouse INT
DECLARE @Countryid INT
DECLARE @CountryidCount INT
DECLARE @Debug INT
DECLARE @HotelCustomerNumber1 int
DECLARE @HotelNumber INT
DECLARE @FolioNumber INT
DECLARE @Cnt INT
DECLARE @DummyOriginalGlobalTransactionNumber INT
DECLARE @UseCashDesk BIT
DECLARE @CashDesk INT
DECLARE @Status INT
DECLARE @tmpWareNumber INT
DECLARE @tmpWareNumberInhouse INT
DECLARE @tmpPayment INT
DECLARE @tmpPaymentInhouse INT
DECLARE @AutoDepartment INT
DECLARE @tmpWareNumberDep INT
DECLARE @tmpPaymentDep INT

DECLARE @DepositWarenumber INT

DECLARE @SystemDate SMALLDATETIME
DECLARE @ShownName smallint
DECLARE @Iden INT

SET @Debug = 0

BEGIN TRY
if (@Referencenumber <= 0)
  RAISERROR('Error in storedprocedure <<OnlinePostering>>: @Referencenumber <= 0. ',15,1)

Select @CentralBookingType = Convert(Integer, Keyvalue) From HotelSetup WITH (NOLOCK) WHERE SearchKey = 'CentralBookingType'
if isnull(@CentralBookingType,0)=0 SET @CentralBookingType = 0

IF ISNULL(@AOverwriteCheckForMultipleTransactions,0) = 0
BEGIN
  IF EXISTS(SELECT * FROM Folios WITH (NOLOCK) WHERE ReferenceNumber = @ReferenceNumber)
  BEGIN
	IF EXISTS(SELECT * FROM Transactions T WITH (NOLOCK) INNER JOIN Folios F WITH (NOLOCK) ON T.FolioNumber = F.FolioNumber AND ReferenceNumber = @ReferenceNumber AND Payment IN (11,12))
	BEGIN
		IF @Note LIKE 'OTA'
			RETURN
		RAISERROR('Error in storedprocedure <<OnlinePostering>>: This SP is called multiple times',15,1)
	END
  END
END

SET @AGuestNumber = ISNULL(@AGuestNumber, 0)

IF ISNULL(@AUserId, 0) <= 0
BEGIN
  SELECT @UserId = Keyvalue FROM Hotelsetup WITH (NOLOCK) WHERE Searchkey = 'PicassoOnlinePosteringUserIdNumber'
  IF ISNULL(@UserId,0) <= 0
	SELECT @UserId = DefaultValue FROM HotelSetup_DefaultValues WITH (NOLOCK) WHERE Searchkey = 'PicassoOnlinePosteringUserIdNumber'
  IF ISNULL(@UserId,0) <= 0
    SELECT TOP 1 @UserId = UserIDNumber FROM Personel WITH (NOLOCK) WHERE UserIDCode='PicassoOnline'
  IF ISNULL(@UserId,0) <= 0
    SELECT TOP 1 @UserId = UserIDNumber FROM Personel WITH (NOLOCK)
END
ELSE
  SET @UserId = @AUserId

SELECT @HotelCustomerNumber1 = Customer.CustomerNumber, @HotelNumber = Customer.HotelNumber 
FROM ReservationMain WITH (NOLOCK) 
INNER JOIN Customer WITH (NOLOCK) ON Customer.HotelNumber = ReservationMain.HotelNumber 
  AND ReferenceNumber = @ReferenceNumber
SELECT @FK_Department = dbo.GetHotelSetupKeyValue ('PicassoOnlinePosteringDepartment', @HotelCustomerNumber1)

SELECT @SystemDate = SYSTEMDATE FROM System WITH (NOLOCK) WHERE Number = 1

SELECT @ShownName = AddressType FROM ReservationAddress WITH (NOLOCK) 
WHERE AddressNumber IN (
  SELECT AddressNumber FROM ReservationAddressXTab WITH (NOLOCK) 
  WHERE ReferenceNumber = @ReferenceNumber AND GuestNumber = @AGuestNumber)
ORDER BY AddressType DESC

IF @DepositFollowupNumber > 0
BEGIN
  SET @Payment = 12
  IF ISNULL(@AOnlineCCType, '') <> ''
  BEGIN
    SELECT TOP 1 @DepositWarenumber = CreditCardTypeWareXTab.WareNumber
    FROM TypeNoName WITH (NOLOCK)
    INNER JOIN CreditCardType WITH (NOLOCK) ON CreditCardType.CreditCardTypeID = TypeNoName.FK_NoName
    INNER JOIN CreditCardTypeWareXTab WITH (NOLOCK) ON CreditCardTypeWareXTab.CreditCardTypeID = CreditCardType.CreditCardTypeID
    INNER JOIN Ware WITH (NOLOCK) ON Ware.WareNumber = CreditCardTypeWareXTab.WareNumber
      AND Ware.Payment = 12 -- Receiced deposit
      AND ISNULL(MarkAsDeleted, 0) = 0
    WHERE TypeNoName.Type_FK = 2 -- Online CC type text
    AND TypeNoName.Name = @AOnlineCCType
    ORDER BY CreditCardType.Number
  END

  IF ISNULL(@DepositWarenumber, 0) = 0
  BEGIN
    SELECT @tmpWareNumberDep = dbo.GetHotelSetupKeyValue ('PicassoOnlinePosteringWarenumber', @HotelCustomerNumber1)
    SELECT @tmpPaymentDep = Payment FROM Ware (NOLOCK) WHERE WareNumber = @tmpWareNumberDep

    IF @tmpPaymentDep = 12
      SET @DepositWarenumber = @tmpWareNumberDep
    ELSE   
      SELECT @DepositWarenumber = WareNumber
      FROM Ware WITH (NOLOCK)
      WHERE Payment = 12
      AND ISNULL(MarkAsDeleted, 0) = 0
  END

  IF ISNULL(@DepositWarenumber, 0) = 0
      RAISERROR('Error in storedprocedure <<OnlinePostering>>: No received deposit ware',15,1)
END
ELSE
BEGIN
  SELECT @tmpWareNumber = dbo.GetHotelSetupKeyValue ('PicassoOnlinePosteringWarenumber', @HotelCustomerNumber1)
  SELECT @tmpWareNumberInhouse = dbo.GetHotelSetupKeyValue ('OnlineInhousePaymentWareNumber', @HotelCustomerNumber1)

  SELECT @tmpPayment = Payment FROM Ware (NOLOCK) WHERE WareNumber = @tmpWareNumber
  SELECT @tmpPaymentInhouse = Payment FROM Ware (NOLOCK) WHERE WareNumber = @tmpWareNumberInhouse

  IF ISNULL(@AWareNumber, 0) <= 0
  BEGIN
    SET @WareNumber = 0

    IF ISNULL(@AOnlineCCType, '') <> ''
    BEGIN
      SELECT TOP 1 @Warenumber = CreditCardTypeWareXTab.WareNumber
      FROM TypeNoName WITH (NOLOCK)
      INNER JOIN CreditCardType WITH (NOLOCK) ON CreditCardType.CreditCardTypeID = TypeNoName.FK_NoName
      INNER JOIN CreditCardTypeWareXTab WITH (NOLOCK) ON CreditCardTypeWareXTab.CreditCardTypeID = CreditCardType.CreditCardTypeID
      INNER JOIN Ware WITH (NOLOCK) ON Ware.WareNumber = CreditCardTypeWareXTab.WareNumber
        AND Ware.Payment = @tmpPayment
        AND ISNULL(MarkAsDeleted, 0) = 0
      WHERE TypeNoName.Type_FK = 2 -- Online CC type text
      AND TypeNoName.Name = @AOnlineCCType
      ORDER BY CreditCardType.Number
    END

    IF ISNULL(@Warenumber, 0) <= 0
      SET @Warenumber = @tmpWareNumber

    IF ISNULL(@WareNumber, 0) = 0
      RAISERROR('Online entry ware number is empty. Set value in HotelSet - Basc - Online', 15, 1)
  END
  ELSE
    SET @Warenumber = @AWareNumber
    
  IF ISNULL(@AWareNumberInHouse, 0) <= 0
  BEGIN
    IF ISNULL(@AOnlineCCType, '') <> ''
    BEGIN
      SELECT TOP 1 @WareNumberInhouse = CreditCardTypeWareXTab.WareNumber
      FROM TypeNoName WITH (NOLOCK)
      INNER JOIN CreditCardType WITH (NOLOCK) ON CreditCardType.CreditCardTypeID = TypeNoName.FK_NoName
      INNER JOIN CreditCardTypeWareXTab WITH (NOLOCK) ON CreditCardTypeWareXTab.CreditCardTypeID = CreditCardType.CreditCardTypeID
      INNER JOIN Ware WITH (NOLOCK) ON Ware.WareNumber = CreditCardTypeWareXTab.WareNumber
        AND Ware.Payment = @tmpPaymentInhouse
      WHERE TypeNoName.Type_FK = 2 -- Online CC type text
      AND TypeNoName.Name = @AOnlineCCType
      AND ISNULL(MarkAsDeleted, 0) = 0
      ORDER BY CreditCardType.Number
    END
    IF ISNULL(@WareNumberInhouse, 0) <= 0
      SET @WareNumberInhouse = @tmpWareNumberInhouse
  END
  ELSE
    SET @WareNumberInhouse = @AWareNumberInhouse

  SELECT @Payment = Payment FROM Ware WITH (NOLOCK) Where WareNumber = @WareNumber
  SELECT @PaymentInhouse = Payment FROM Ware WITH (NOLOCK) Where WareNumber = @WareNumberInhouse
END

SELECT @CountryidCount = Count(*) FROM Hotelsetup WITH (NOLOCK) Where Searchkey = 'CountryCode'
IF @CountryidCount > 0
  SELECT @Countryid = Keyvalue FROM Hotelsetup WITH (NOLOCK) Where Searchkey = 'CountryCode'
ELSE
  SET @Countryid = 1

IF @Debug = 1
begin
  print '******************************'
  print @Referencenumber 
  print @UserId
  print @WareTextOverwrite
  print CONVERT(varchar(50),@TotalPrice)
  print @Countryid
  print @FK_Department
  print @Warenumber
  PRINT @WareNumberInhouse
  print @Note
  print @TransNrShowOnBill 
  PRINT @DepositWarenumber
  print '******************************'
END

SELECT @UseCashDesk = dbo.GetHotelSetupKeyValue ('FiscalPrinterSweden', @HotelCustomerNumber1)
SET @UseCashDesk = ISNULL(@UseCashDesk, 0)

DECLARE @ArrivalDate CHAR(8)
DECLARE @ArrivalTime CHAR(5)

SELECT @Status = Status, @ArrivalDate = ArrivalDate, @ArrivalTime = ArrivalTime
FROM Reservations WITH (NOLOCK)
WHERE ReferenceNumber = @ReferenceNumber AND GuestNumber = @AGuestNumber

IF @Payment = 12
BEGIN
  IF @DepositFollowupNumber > 0
  BEGIN
    IF ISNULL(@AGlobalTransactionNumber, 0) <= 0
      EXEC GetNextNumber 'GLOBALTRANSACTIONIDENTITY', 1, @AGlobalTransactionNumber OUTPUT

    IF @UseCashDesk = 1
    BEGIN
      EXEC GetCashDeskForOnline @HotelCustomerNumber1, @CashDesk OUTPUT

      EXEC Postering 0, 0, 1, @Referencenumber, @AGuestNumber, 0, @UserId, 0, 
        0, 0, 0, 0, @WareTextOverwrite, 1, @TotalPrice, @Countryid, 
        0, 0, 0, 0, @FK_Department, @DepositWarenumber, @Payment, @AGlobalTransactionNumber, 
        0, 0, @Note, @TransNrShowOnBill OUTPUT, -1, -1, 0, 
        @DepositFollowupNumber, 0, 0, 0, 0, 0, 
        @DummyOriginalGlobalTransactionNumber OUTPUT, @CashDesk
    END
    ELSE
      EXEC Postering 0, 0, 1, @Referencenumber, @AGuestNumber, 0, @UserId, 0, 
        0, 0, 0, 0, @WareTextOverwrite, 1, @TotalPrice, @Countryid, 
        0, 0, 0, 0, @FK_Department, @DepositWarenumber, @Payment, @AGlobalTransactionNumber, 
        0, 0, @Note, @TransNrShowOnBill OUTPUT, -1, -1, 0, 
        @DepositFollowupNumber

    EXEC OnlinePostChangeStatus @ReferenceNumber, @AGuestNumber, @SystemDate, @ShownName, @UserId, @HotelNumber
  END
  ELSE
  BEGIN  
    -- Followup
    DECLARE
      @DepositText varchar(50),
      @Departments varchar(50),
      @UserIdNumber int

    SET @DepositText = 'Depositum Online'

    DECLARE @SystemDateTime DATETIME
    EXEC SystemDateTime '', @SystemDateTime OUTPUT

    INSERT INTO FollowUp ([Date], Type, DepositAmount, Priority, State, Note, Shownname, CreatedDate, CreatedBy, UserCreated, SubType, RuleNumber, OverWritten, Tag, ReservationStatus, HotelNumber)
    VALUES (@SystemDate, 15, @TotalPrice, 17, 3, @DepositText, @ShownName, @SystemDateTime, @UserId, NULL, NULL, 1, 0, NULL, NULL, @HotelNumber)

    SELECT @Iden = @@Identity

    INSERT INTO ReservationFollowUpXTab (FollowUpNumber, ReferenceNumber, GuestNumber)
    VALUES (@Iden, @Referencenumber, @AGuestNumber)

    SELECT @Departments = KeyValue FROM HotelSetup WITH (NOLOCK) WHERE SearchKey = 'FollowUpDefaultDepartmentsDeposits'
    IF @Departments <> ''
    DECLARE db_cur CURSOR FOR
      SELECT DISTINCT Personel.UserIdNumber 
      FROM Personel WITH (NOLOCK) 
      INNER JOIN PersonelDepartmentsXtab pd WITH (NOLOCK) ON pd.UserIdNumber = Personel.UserIdNumber 
        AND pd.FK_Department IN (SELECT number FROM DBO.iter_intlist_to_table(@Departments))
    OPEN db_cur 

    FETCH NEXT FROM db_cur INTO @UserIdNumber

    WHILE @@fetch_status = 0
    BEGIN
      INSERT INTO PersonalFollowUpXTab (UserIdNumber, FollowUpNumber) VALUES (@UserIdNumber, @Iden)
      FETCH NEXT FROM db_cur INTO @UserIdNumber
    END
    DEALLOCATE db_cur
  END
END

IF ISNULL(@DepositFollowupNumber, 0) <= 0
BEGIN
  IF ISNULL(@AGlobalTransactionNumber, 0) <= 0
    EXEC GetNextNumber 'GLOBALTRANSACTIONIDENTITY', 1, @AGlobalTransactionNumber OUTPUT

  IF @Status >= 5 -- inhouse / Use the inhouse payment ware
  BEGIN
    IF ISNULL(@WareNumberInhouse, 0) <= 0
      RAISERROR('Error in storedprocedure <<OnlinePostering>>: Hotelsetup->Basic->Online->Payment for inhouse res. setting is required but not set. ',15,1)

    SET @Warenumber = @WareNumberInhouse 
    SET @Payment = @PaymentInhouse
  END

  IF @ASetResGuaranteed = 1
    EXEC OnlinePostChangeStatus @ReferenceNumber, @AGuestNumber, @SystemDate, @ShownName, @UserId, @HotelNumber

  IF @UseCashDesk = 1
  BEGIN
    EXEC GetCashDeskForOnline @HotelCustomerNumber1, @CashDesk OUTPUT

    EXEC Postering 0, 0, 1, @Referencenumber, @AGuestNumber, 0, @UserId, 0, 
      0, 0, 0, 0, @WareTextOverwrite, 1, @TotalPrice, @Countryid, 
      0, 0, 0, 0, @FK_Department, @Warenumber, @Payment, @AGlobalTransactionNumber, 
      0, 0, @Note, @TransNrShowOnBill OUTPUT, -1, -1, 0, 
      0, 0, 0, 0, 0, 0, 
      @DummyOriginalGlobalTransactionNumber OUTPUT, @CashDesk
  END
  ELSE
    EXEC Postering 0, 0, 1, @Referencenumber, @AGuestNumber, 0, @UserId, 0, 0, 0, 0, 0, @WareTextOverwrite, 1, @TotalPrice, @Countryid, 0, 0, 0, 0, @FK_Department, @Warenumber, @Payment, @AGlobalTransactionNumber, 0, 0, @Note, @TransNrShowOnBill OUTPUT

  IF (ISNULL(@AOnlinePaymentId, '') <> '' OR ISNULL(@AOnlineTransactionId, '') <> '') AND @TransNrShowOnBill > 0
  BEGIN
    SET @Iden = -1

    SELECT @Iden = Id
    FROM OnlinePayment WITH (NOLOCK)
    WHERE OnlinePaymentId = @AOnlinePaymentId

    IF ISNULL(@Iden, 0) > 0
    BEGIN
      UPDATE OnlinePayment
      SET OnlineTransactionId = @AOnlineTransactionId
      WHERE Id = @Iden

      UPDATE TransactionOnlinePaymentXtab
      SET FK_TransactionNumber = @TransNrShowOnBill
      WHERE FK_OnlinePaymentId = @Iden
      IF @@ROWCOUNT = 0
        INSERT INTO TransactionOnlinePaymentXtab (FK_TransactionNumber, FK_OnlinePaymentId) VALUES (@TransNrShowOnBill, @Iden)
    END
    ELSE
    BEGIN
      INSERT INTO OnlinePayment (OnlinePaymentId, OnlineTransactionId) VALUES (@AOnlinePaymentId, @AOnlineTransactionId)
      SELECT @Iden = @@Identity
      INSERT INTO TransactionOnlinePaymentXtab (FK_TransactionNumber, FK_OnlinePaymentId) VALUES (@TransNrShowOnBill, @Iden)
    END
  END
END

IF ISNULL(@ACreditCardFee, 0) > 0 OR ISNULL(@AInvoiceFee, 0) > 0
BEGIN
  SELECT @FolioNumber = FolioNumber FROM Folios WITH (NOLOCK) WHERE ReferenceNumber = @ReferenceNumber AND GuestNumber = @AGuestNumber

  SELECT @Cnt = COUNT(*) FROM Transactions WITH (NOLOCK) WHERE FolioNumber = @FolioNumber AND MovedDeleted = 1 AND DepositFollowupNumber = @Iden
  IF (@Cnt > 0)
  BEGIN
    DECLARE @Str VARCHAR(250)
    SET @Str = 'Error in storedprocedure <<OnlinePostering>>: MovedDeleted = 1'+convert(varchar(100), @FolioNumber)
    RAISERROR(@Str, 15, 1)
  END

  SELECT TOP 1 @AutoDepartment = PK_Department 
  FROM Departments WITH (NOLOCK) 
  WHERE AutoCharge = 1 
  AND ((MarkAsDeleted=0) OR (MarkAsDeleted IS NULL))  
  AND ((@CentralBookingType NOT IN (3,7)) OR (Departments.HotelNumber IN (SELECT HotelNumber FROM Customer WITH (NOLOCK) WHERE CustomerTypeNumber = 7 AND CustomerNumber = @HotelCustomerNumber1)))
  ORDER BY SortNumber

  IF ISNULL(@AutoDepartment, 0) = 0
  SELECT TOP 1 @AutoDepartment = PK_Department FROM Departments WITH (NOLOCK) WHERE ((MarkASDeleted=0) OR (MarkASDeleted IS NULL)) ORDER BY SortNumber
END

DECLARE @FeeWareNumber INT
DECLARE @TNrShowOnBill INT
DECLARE @FeeAsArr BIT
DECLARE @FeeName VARCHAR(100)
DECLARE @Ident INT

IF ISNULL(@ACreditCardFee, 0) > 0
BEGIN
  SELECT @FeeAsArr = Keyvalue FROM Hotelsetup WITH (NOLOCK) WHERE Searchkey = 'OnlineCreditCardFeeAsArrangement'
  
  SELECT @FeeWareNumber = WareNumber, @FeeName = WareName
  FROM Ware WITH (NOLOCK)
  INNER JOIN WareGroups WITH (NOLOCK) ON WareGroups.WareGroupNumber = Ware.WareGroupNumber
  WHERE Ware.SortNumber = 6
  AND WareGroups.Payment = 4 -- fees
  
  IF ISNULL(@FeeAsArr, 0) = 1
  BEGIN
    INSERT INTO ArrangementLines (Date, PacketItemNumber, Time, Price, Pieces, WareText, PlaceText, WareNumber, HallNumber, FK_EXDepartment, FK_HallNumber)
    VALUES (@ArrivalDate, NULL, @ArrivalTime,  @ACreditCardFee, 1, @FeeName, '', @FeeWareNumber, NULL, @AutoDepartment, NULL)
    SET @Ident = @@IDENTITY
    INSERT INTO ArrangementReservationsXtab VALUES (@Ident, @Referencenumber, @AGuestNumber, 0)
  END    
  ELSE
    EXEC OnlinePosteringExt @FeeWareNumber, @HotelCustomerNumber1, @FolioNumber, @ACreditCardFee, 1, '', @TNrShowOnBill OUTPUT
END

IF ISNULL(@AInvoiceFee, 0) > 0
BEGIN
  SELECT @FeeAsArr = Keyvalue FROM Hotelsetup WITH (NOLOCK) WHERE Searchkey = 'OnlineInvoiceFeeAsArrangement'
  
  SELECT @FeeWareNumber = WareNumber, @FeeName = WareName
  FROM Ware WITH (NOLOCK)
  INNER JOIN WareGroups WITH (NOLOCK) ON WareGroups.WareGroupNumber = Ware.WareGroupNumber
  WHERE Ware.SortNumber = 3
  AND WareGroups.Payment = 4 -- fees
  
  IF ISNULL(@FeeAsArr, 0) = 1
  BEGIN
    INSERT INTO ArrangementLines (Date, PacketItemNumber, Time, Price, Pieces, WareText, PlaceText, WareNumber, HallNumber, FK_EXDepartment, FK_HallNumber)
    VALUES (@ArrivalDate, NULL, @ArrivalTime,  @AInvoiceFee, 1, @FeeName, '', @FeeWareNumber, NULL, @AutoDepartment, NULL)
	  SET @Ident = @@IDENTITY
    INSERT INTO ArrangementReservationsXtab VALUES (@Ident, @Referencenumber, @AGuestNumber, 0)
  END    
  else
    EXEC OnlinePosteringExt @FeeWareNumber, @HotelCustomerNumber1, @FolioNumber, @AInvoiceFee, 1, '', @TNrShowOnBill OUTPUT
END
END TRY
BEGIN CATCH
  DECLARE @ErrorMessage NVARCHAR(MAX)
  DECLARE @ErrorSeverity INT
  DECLARE @ErrorState INT

  SELECT @ErrorMessage = ERROR_MESSAGE() + ' Line ' + CAST(ERROR_LINE() as nvarchar(5)), @ErrorSeverity = ERROR_SEVERITY(), @ErrorState = ERROR_STATE()
  
  RAISERROR (@ErrorMessage, @ErrorSeverity, @ErrorState)
END CATCH