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) = '' AS
SET NOCOUNT ON

/*
    Created by Troels Buch Marts 2005
    
    Changes:
    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

    NOTES: 	- 
*/

DECLARE @cnt1 INT
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 @AllotmentNumber INT
DECLARE @AllotmentOverbook BIT
DECLARE @tmpOverbook TINYINT
DECLARE @ArrivalDT DATETIME
DECLARE @DepartureDT DATETIME
DECLARE @RoomTypeNumber INT
DECLARE @s VARCHAR(200)

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
  SELECT @cnt1 = COUNT(*) FROM Folios WITH (NOLOCK) WHERE ReferenceNumber = @ReferenceNumber
  IF @cnt1 > 0
  BEGIN
    SELECT @cnt1 = COUNT(*) FROM Transactions T WITH (NOLOCK) 
    INNER JOIN Folios F WITH (NOLOCK) ON T.FolioNumber = F.FolioNumber AND ReferenceNumber = @ReferenceNumber AND Payment IN (11,12)
  
    IF @cnt1 > 0
      RAISERROR('Error in storedprocedure <<OnlinePostering>>: This SP is called multiple times',15,1)
  END
END

SET @AGuestNumber = ISNULL(@AGuestNumber, 0)

IF ISNULL(@AUserId, 0) <= 0
BEGIN
  SELECT @UserId = Keyvalue FROM Hotelsetup WITH (NOLOCK) WHERE Searchkey = 'PicassoOnlinePosteringUserIdNumber'
  IF @UserId <= 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

    SET @AllotmentOverbook = 0

    SELECT @AllotmentNumber = AllotmentNumber
    FROM ReservationMain WITH (NOLOCK)
    WHERE ReferenceNumber = @Referencenumber

    IF @AllotmentNumber > 0
    BEGIN
      DECLARE #db_cur CURSOR LOCAL READ_ONLY FAST_FORWARD FOR
        SELECT CONVERT(DATETIME,
        CASE WHEN @AGuestNumber = 0 THEN
          rrl.ArrivalDate
        ELSE
          r.ArrivalDate
        END, 112),
        CONVERT(DATETIME,
        CASE WHEN @AGuestNumber = 0 THEN
          rrl.DepartureDate
        ELSE
          r.DepartureDate
        END, 112),
        ISNULL(RoomTypes.RoomTypeNumber, rrl.BookedTypeNumber)
        FROM ReservationRoomLine rrl WITH (NOLOCK)
        INNER JOIN ReservationRoomLineXTab rrlx WITH (NOLOCK) ON rrlx.LineNumber = rrl.LineNumber
          AND rrlx.ReferenceNumber = @Referencenumber
          AND rrlx.GuestNumber = @AGuestNumber
        INNER JOIN Reservations r WITH (NOLOCK) ON r.ReferenceNumber = rrlx.ReferenceNumber
          AND r.GuestNumber = rrlx.GuestNumber
        LEFT OUTER JOIN Rooms WITH (NOLOCK) ON Rooms.RoomNumber = rrl.RoomNumber
        LEFT OUTER JOIN RoomTypes WITH (NOLOCK) ON RoomTypes.RoomTypeNumber = Rooms.RoomTypeNumber
        WHERE r.Status <= 5
      OPEN #db_cur
      FETCH NEXT FROM #db_cur INTO @ArrivalDT, @DepartureDT, @RoomTypeNumber

      WHILE @@FETCH_STATUS = 0 AND @AllotmentOverbook = 0
      BEGIN
        EXEC AllotmentCheckForOverbooking @AllotmentNumber, @RoomTypeNumber, @ArrivalDT, @DepartureDT, @tmpOverbook OUTPUT

        IF @tmpOverbook > 0
          SET @AllotmentOverbook = 1

        FETCH NEXT FROM #db_cur INTO @ArrivalDT, @DepartureDT, @RoomTypeNumber
      END
    END

    IF @AllotmentOverbook = 0
    BEGIN
      DECLARE @ChangeStatusOnAllSubReservations BIT

      SELECT @ChangeStatusOnAllSubReservations = CAST(KeyValue AS BIT) FROM HotelSetup WITH (NOLOCK) WHERE SearchKey = 'ChangeStatusOnAllSubReservations'
      SET @ChangeStatusOnAllSubReservations = ISNULL(@ChangeStatusOnAllSubReservations, 0)

      UPDATE Reservations 
      SET Status = 2 
      WHERE ReferenceNumber = @Referencenumber 
      AND (@ChangeStatusOnAllSubReservations = 1 OR GuestNumber = @AGuestNumber)
      AND Status < 5 

      UPDATE rrl
      SET StatusRL = 2
      FROM ReservationRoomLine rrl WITH (NOLOCK)
      INNER JOIN ReservationRoomLineXTab rrlx WITH (NOLOCK) ON rrlx.LineNumber = rrl.LineNumber
        AND rrlx.ReferenceNumber = @Referencenumber
        AND (@ChangeStatusOnAllSubReservations = 1 OR rrlx.GuestNumber = @AGuestNumber)
      WHERE StatusRL < 5

      UPDATE ReservationConferenceLine
      SET TableStatus = 2
      WHERE ReferenceNumber = @Referencenumber
      AND (@ChangeStatusOnAllSubReservations = 1 OR GuestNo = @AGuestNumber)
      AND TableBooking = 1
      AND TableStatus < 5
      
      SET @s = 'Status changed to Guaranteed'

      INSERT INTO FollowUp ([Date], Type, Priority, State, Note, Shownname, CreatedDate, CreatedBy, UserCreated, SubType, OverWritten, ReservationStatus, HotelNumber)
      VALUES (@SystemDate, 5, 17, 3, @s, @ShownName, @SystemDate+convert(varchar, getdate(), 108), @UserId, 0, 2, 0, 2, @HotelNumber)

      SELECT @Iden = @@Identity

      INSERT INTO ReservationFollowUpXTab (FollowUpNumber, ReferenceNumber, GuestNumber)
      VALUES (@Iden, @Referencenumber, @AGuestNumber)
    END
  END
  ELSE
  BEGIN  
    -- Followup
    DECLARE
      @DepositText varchar(50),
      @Departments varchar(50),
      @UserIdNumber int

    SET @DepositText = 'Depositum Online'

    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, @SystemDate+convert(varchar, getdate(), 108), @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>>: Online Inhouse Payment Ware <= 0. ',15,1)

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

  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
  BEGIN
    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
  END

  IF (ISNULL(@AOnlinePaymentId, '') <> '' OR ISNULL(@AOnlineTransactionId, '') <> '') AND @TransNrShowOnBill > 0
  BEGIN
    INSERT INTO OnlinePayment (OnlinePaymentId, OnlineTransactionId) VALUES
      (@AOnlinePaymentId, @AOnlineTransactionId)
    SELECT @Iden = @@Identity
    INSERT INTO TransactionOnlinePaymentXtab (FK_TransactionNumber, FK_OnlinePaymentId) VALUES
      (@TransNrShowOnBill, @Iden)
  END
END

IF ISNULL(@ACreditCardFee, 0) > 0
BEGIN
  SELECT @FolioNumber = FolioNumber FROM Folios WITH (NOLOCK) WHERE ReferenceNumber = @ReferenceNumber AND GuestNumber = @AGuestNumber --AND HotelCustomerNumber = @HotelCustomerNumber1   KJ20060215

  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

  DECLARE @FeeWareNumber INT
  DECLARE @TNrShowOnBill INT
  DECLARE @CCFeeAsArr BIT
  DECLARE @ccFeeName VARCHAR(100)
  DECLARE @Ident INT
  SELECT @CCFeeAsArr = Keyvalue FROM Hotelsetup WITH (NOLOCK) WHERE Searchkey = 'OnlineCreditCardFeeAsArrangement'
  
  SELECT @FeeWareNumber = WareNumber, @ccFeeName = 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(@CCFeeAsArr, 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, @ccFeeName, '', @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
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