CREATE PROCEDURE dbo.Postering @PostForDatetime Datetime, @PostDiscount bit, @PostVAT bit, @PostOnReferenceNumber int, @PostOnGuestNumber smallint, @RoomNumber int, @UserIDNumber int, @FolioNumber int, 
  @TransferToReferenceNumber int, @TransferToGuestNumber int, @TransferToAddressTypeNumber int, @TransferToFolioNumber int, @WareTextOverwrite varchar(150), @Pieces int, @Price money, @CountryNumber int, 
  @PaxAdult smallint, @PaxChild1 smallint, @PaxChild2 smallint, @MovedFolioNumber int, /*@Department char(1)*/ @FK_DepartmentNumber INT, @WareNumber int, @Payment smallint, @GlobalTransactionNumber int, 
  @MovedTransactionNumber int, @Correction bit, @Note varchar(50), @TransNrShowOnBillOnAdd INT OUTPUT, @HotelCustomerNumber int = -1, @ProductWareLinkNumber int=-1, @TakeAccountsFromWareNumber int = 0, 
  @DepositFollowupNumber int = 0, @FirstAddressNumber INT = 0, @AutoReceivedPayment BIT = 0, @FirstGlobaltransactionNumber INT = 0, @ChargedWithCard Bit = 0, @AXPMSTransfer BIT = 0, 
  @AOriginalGlobalTransactionNumber INT = -1 OUTPUT, @ACashDesk INT = -1, @AArrangementLineNumber INT = NULL, @ADoNotGetNewGiftTokenId BIT = 0, @AMainTransactionNumber INT = 0,
  @ATranRelationType INT = 0 AS
SET NOCOUNT ON

/*
 KJ 20241029: Bug: Fix for "Cannot insert the value NULL into column 'FK_CashBox', table 'NO_Hurdal_241028.dbo.TransactionsRelation'; column does not allow nulls".
 KJ 20240326: Bug: Fix for "Reduction by move does not have correct relation added to TransactionTransactionXTab".
 KJ 20240214: Added timeZone.
 KJ 20230918: Bug: TransactionTransactionXTab has wrong TransactionNumber when reduction my move.
 KJ 20230525: Ext: Ext: OnlinePayment info not related to transaction when transaction is moved. Case #CR4170
 KJ 20210715: Ext: Added TransactionTransactionXtab relation for reduction and split. Type defined in EconomyTL -> TransactionRelationType
 KJ 20200106: Ext: If deleted transaction is precharged and date is in the future, then delete should be done on same date
 KJ 20180927: Bug: Fix for "Reduction on transfer". Case #CR153174
 KJ 20180911: Ext: Added try catch to break out of sp if any exception/error happens
 KJ 20180312: Ext: TransactionTransactionXtab
 KJ 20171120: Bug: Moving Gift token payment is not allowed 
 KJ 20171003: Ext: eaise error if post of received deposit on sales or Invoice
 KJ 20161215: Bug: Fix for "Error when split of manuel room/hall when original post is made with out package". Case #CR117443 
 KJ 20160915: Bug: Fix for "Reduction by pieces > 0 on menu ware results in wrong price". Case #CR112651
 KJ 20160221: Ext: Added @ADoNotGetNewGiftTokenId for GiftToken Import. Req #2918
 KJ 20151215: Bug: Fix for "Does not set return value @TransNrShowOnBillOnAdd for reduction". Bug #302
 KJ 20151103: Bug: Fix for "TextOverwrite incorrect for exchange rate part". Case #CR094134
 KJ 20150626: Bug: Fix for "Ware is not posted as menuware when selling more than one pieces". Case #CR089655
 KJ/NB 20150611: Bug: Wrong table number for transfer 
 KJ 20150427: Bug: Added arranagementlinenumber. Handle for multiple precharge.
 KJ 20150326: Ext: Added arranagementlinenumber. Handle for multiple precharge.
 KJ 20150105: Bug: Fix for "Error when post of more than one pieces of a menu ware not in percent". Case #CR081859
--nb20140721 FolioIdentity discontinued
 KJ 20140624: Ext: Menu ware split in whole amount. Req #1561
 KJ 20140611: Ext: CashDesk per hotel. Case #CR073269
 KJ 20131121: Bug: Fix for "Wanted deposit not posted on guest folio".
 KJ 20131113: Bug: Fix for "Reduction (without move) results in a clean delete". Reuse the part that make transactions when reduction is made by moveing
 KJ 20131112: Bug: Fix for "Wrong GlobalTransactionNumber when split of Menu ware".
 KJ 20131113: Bug: Fix for "Wrong GlobalTransactionNumber when split of product".
 KJ 20131105: Bug: Fix for "Reduction/split on menu ware is done with wrong price". Bug #101
 KJ 20131009: Bug: Fix for "reduction on room hall not done with correct price". Bug #100
 KJ 20130418: New: Added "More provision wares is possible. Setup per Roomtype". Req #1575
 KJ 20130321: Bug: Fix for "Error posting from interface when running mixed resources and different hotel on reservation". Case #CR053993
 KJ 20130104: Ext: Added partly redeem. Req #933
 KJ 20120829: Bug: Fix for "Wrong pieces when reduction"
 KJ 20120829: Bug: Fix for "Wrong OriginalGlobalTransactionNumber when reduction".
 KJ 20120826: Ext: Reduction on room/hall postings. Req #1313
 KJ 20120823: Ext: Reduction on menware. Req #1313
 KJ 20120817: Bug: Possible fix for "Wrong ProductWareLinkNumber"
 KJ 20120116: Bug: Fix for "Wrong text when overwrite ware test on menuware". Case #CR038721 
 KJ 20120116: Bug: Fix for "OriginalGlobalTransactionNumber is wrong if reduction". Case #CR038698
 KJ 20120113: Bug: Fix for "making wrongly menuware setup more secure". Case #CR38735
 KJ 20110522: Bug: Fix for "Only new ProductWareLinkNumber if existing is greater than 0". Case #CR032707.
 KJ 20110815: Ext: New ProductWareLinkNumber when move and delete transactions 
 KJ 20110627: Ext: Discount on menuware
 KJ 20101222: Bug: Fix for "Gift certificate number not correct in note field on transactions"
 KJ 20101207: Bug: Fix for "Globaltran number wrong for redeem gift certificate"
 KJ 20100923: Bug: Fix for "Can not insert the value NULL into Original GlobalTransactionNumber" 
 KJ 20100816: Making postering more secure to prevent use of deleted hotel
 KJ 20100811: Bug: FIx for "Can not insert the value NULL into FK_TransactionNumber" - for TransactionDeleteNote
 KJ 20100708: Bug: Fix for "Wrong userid on TransactionDeleteNote"
 KJ 20100707: Bug: Fix for "Exchangerate and countryNumber wrong for delete valuta transactions"
 KJ 20100702: Bug: Fix for "Cashbox not correct when transfer as ware" case# CR015805
 KJ 20100602: Bug: Fix for "Sometimes customer/hotel is deleted"
 KJ 20100312: Bug: Fix for "Cashbox not correct when running fiscal sweden and no cashbox is running"
 KJ 20100119: Bug: Fix for "Move of manuel room/hall does not move package transactions"
 KJ 20100104: Bug: Fix for "Only call PostGiftCertificate if @Correction = 0"
 KJ 20091207: Ext: Added Cash Desk
 KJ 20091102: Bug: Fix for "Handle delete transactions that has been moved around a couple of different folios"
 KJ 20091029: Yet another try to fix the "Move delete problem"
 KJ 20091020: Making the MoveDelete check more secure
 KJ 20090827: Bug: Fix for "Secure for MoveDeleted is posted wrong"
 KJ 20090825: Bug: Fix for "Posted on wrong hotelCustomerNumber when running Domino"
 KJ 20090824: Bug: Fix for "PicassoInterface.dll not working for guestno>0 and not Domino"
 KJ 20090210: Bug: Fix for "Received deposit posted on wrong account when auto deposit from cashier"
 KJ 20090129: Bug: Possible fix for Lock timeout.
 KJ 20090107: Ext: Added post GiftCertificate
 KJ 20081222. Ext: Added OriginalGlobalTransactionNumber
 KJ 20081215: Opt: Optimized for move/delete overnight/day products by a factor more than 150 ;-)
 KJ 20081212: Opt: Optimized for move transactions.
 KJ 20081128: Bug: Fix for "Post menuware delete/moved/reduction error"
 KJ 20081110: Bug: Fix for "Always post checkin deposit on the folio given by input param"
 KJ 20081022: Bug: Fix for @VatValueWare sometimes NULL when posting Discount
 nb 20080916: Insure posting using RoomNumber ends on the correct hotel
 KJ 20080828: Bug: Fix for "Do not post on wrong hotel for pay/tv" case #3937
 KJ 20080825: Bug: Fix for "Always post checkin deposit on the folio given by input param"
 KJ 20080526: Bug: Fix for "Menu ware not posted correctly when reduction"
 KJ 20080523: Bug: Fix for "Handle for Menuware and AllowZero prices."
 KJ 20080522: Bug: Fix for "Pieces for delete transactions wrong"
 KJ 20080430: Bug: Fix for "Not able to post negative amount"
 KJ 20080417: Ext: Handle delete of menuware
 MR 20080327: Ext: Added use of MenuWares
 KJ 20071116: Bug fix "Wanted deposit posted on wrong foliotype if only tablebooking"
 KJ 20070824: Ext: Added @SeparateEconomyByStaffDep. Used by Gl. Skivehus for Transfer from Babara to Hotel
 KJ 20070704: Bug: Fix for "Wrong department for phone transactions when running domino"
 KJ 20070503: Bug if normal post the negative pieces are not posted correct.
 KJ 20070503: Bug Fix for Delete owner transactions wrong. Field Debit not correct.
 KJ 20070410: Department rewrite
 KJ 20070201: Fix fir XPMSTransfer enabled for negative amount
 KJ 20070123: PosteringAsTransfer enabled for negative amount
 KJ 20061221: Added support for XPMSTransfer.
 KJ 20061122: Moved transfer as ware to seperat sp
nb20061108 Kitchen - Mark changed only transactions moved same date. general extension
NB 20061101 Transfer as ware - Balance transaction account as the orig transaction.
 KJ 20061031 Payment on transfer as ware changed to 0
 KJ 20061024 Fix for transfer not working
 KJ 20060911 On transfer transactions then update the guestnumber on the moved to folio
 KJ 20060908 Added @TransferVatValue to add vatvalue when transfer as ware
nb20060901 Fix Locktimeout back to original value at the end
 KJ 20060824 Fix for Cannot insert the value null into PriceOverwrite (happens when giving discount on transfers)
 KJ 20060808 Added Raise if @RealDateTimeForTransaction > @PostForDatetime Post back in time is not allowed.
 KJ 20060629 Exchangerate not correct. Error on Park In. CC-manager case #8438
 KJ 20060607 Transfer as Ware implemented
 NB 20060526 Temporary change in dealing with account numbers when ware of type transfer. Working as transfer payment.
 KJ 20060509 Autocharge changed
 KJ 20060420 Added @ShowPrint
 KJ 20060420 Fix for provision rate 9.5 is rounded to 10
 nb20060217 Somebody have removed the LOCK_TIMEOUT. It is needed do not remove.
 nb 20060207 CountryNumber requried Safety implemented and @CountryNumber replaced with @MyCountryNumber
 KJ 20060117 Fix for "PayTv discount added to GetDiscountRate" (Depends on new field in ReservationAddress added in version 3.36)
 KJ 20051010 BUG: Using Rooms.Number instead of Rooms.RoomNumber -> Interface not posted if running chain
 nb20050920 bug last bug related error in reduction uses gsame globaltransnr and results in error later on deletion
 KJ 20050825 Removed update GlobalTransactionIdentity using GetNextNumber instead
 nb/kj20050818 fejl ved flytning og sletning hvis forkert Globaltransactionnumber (MovedTransactionNumber)
 nb/kj20050818 fejl ved flytning og sletning hvis forkert Globaltransactionnumber
 KJ 20050817 Fix for HotelCustomerNumber = -1 when called from interfaces.
 KJ20050620 Removed AccountDaily
 nb20050616 Table lock in transactions removed (GlobalTransactionNumber Index added)
 KJ20050530 Added raise error when HotelCustomerNumber = -1 and hotel is chain
 JP20050526 changed to use GetNextNumber SP
 nb20050411 Deleted kitchen transaction after move, mark only the last transaction as changed
 nb20050411 Print Moved kitchen transaction keyValue fixed
 Rettet d. 17/03-2005 af KS Imp. @ChargedWithCard
 Rettet d. 15/03-2005 af KS Imp. transfer between hotels when domino
 nb20050314 Printed kitchen transactions disable print on move to another folio
 Rettet d. 08/03-2005 af KS Delete addon with the same accountnumbers as charged
 nb20050107 Ext Mark changed only kitchentransactions moved to Table folios
 nb20050107 Bug Wrong tableBooking key Tablebooking -> TableBookingEnabled
 Rettet d. 22/12-2004 af KS Bug not mark as moveddeleted in 21/12
 Rettet d. 21/12-2004 af KS Delete discount with the same accountnumbers as charged
 Rettet d. 29/03-2004 Added folionumber on transferfrom when table
*/

DECLARE @ShowPrint BIT
SET @ShowPrint = 0

DECLARE @FolioType INT
DECLARE @s VARCHAR(500)

IF @FolioNumber > 0 AND @Payment = 12 -- Received deposit
BEGIN
  SELECT @FolioType = CASE
    when ISNULL(FRX.FolioNumber, 0) > 0 THEN 5
    when ISNULL(F.ReferenceNumber, 0) = 0 and ISNULL(F.ReservationAddressNumber , 0) = 0 THEN 1
    when ISNULL(F.ReferenceNumber, 0) = 0 and ISNULL(F.ReservationAddressNumber , 0) > 0 THEN 2
    when ISNULL(F.ReferenceNumber, 0) > 0 and ISNULL(F.FolioNumber, 0) > 0 THEN 3
  END
  FROM dbo.Folios F with (nolock)
  LEFT JOIN dbo.FolioRestResTableChairsXTab FRX with (nolock) on FRX.FolioNumber = F.FolioNumber
  WHERE F.FolioNumber = @FolioNumber
  
  IF @FolioType IN (1,2)
  BEGIN
    SET @s = 'Error in storedprocedure <<postering>>: Received deposit posted on folio type where not allowed. Folio number: ' + CAST(@FolioNumber AS VARCHAR) + ' Folio Type = ' + CAST(@FolioType AS VARCHAR)
    RAISERROR(@s, 15, 1)
  END
END
ELSE IF @Payment IN (15,16,17) AND ISNULL(@MovedFolioNumber, 0) > 0 -- Gift token payment may not be moved to another folio
BEGIN
  SET @s = 'Error in storedprocedure <<postering>>: Moving Gift token payment is not allowed. Folio number: ' + CAST(@FolioNumber AS VARCHAR)
  RAISERROR(@s, 15, 1)
END

DECLARE @LockTimeOut INT
SET @LockTimeOut = @@LOCK_TIMEOUT
SET LOCK_TIMEOUT 10000 --nb20060217 Do not remove locks will be caused 

BEGIN TRY

Declare @ResultAccountNumber int
Declare @VATAccountNumber int
Declare @BalanceAccountNumber int
Declare @PaymentBalanceAccountNumber int
Declare @VATValueNumber int
Declare @VatValueWare money
Declare @WareText Varchar(150)
Declare @WarePrice money
Declare @WarePriceExVAT money
Declare @VatOfWarePrice money
Declare @CurrentDateStr Char(8)
Declare @RealDateTimeForTransaction DateTime
Declare @CustomerNumber int
Declare @ProductNumber int
Declare @FixedProductPrice bit
Declare @DayProduct bit
Declare @PackageNumber int
Declare @ShowOnBillFlag Bit
Declare @AccountNumber int
Declare @Debit bit
Declare @INVDebit bit
Declare @AddressType Smallint
Declare @WareGroupNumber int
Declare @WareSortNumber smallint
Declare @WareIsHallRoom bit
Declare @SinglePriceToTrans money
Declare @OriginalWareText varchar(100)
Declare @SplitbillNumber int
Declare @SystemDate DateTime
Declare @OriginalDate DateTime
--Declare @ExchangeRate money
Declare @ExchangeRate FLOAT
Declare @DummyTransNrShowOnBillOnAdd int
Declare @TempDepositFollowupNumber int
Declare @ReservationStatus tinyint
Declare @NumberOfCheckinDeposit Int
Declare @AccountType TinyInt
Declare @TempWareNumber Int
Declare @InterfaceNumber Int
Declare @TransferFromRoomNumber Int
Declare @TransferFromTableNumber Int
Declare @TableNumber Int Set @TableNumber = 0
Declare @KitchenStatementNumber Int
Declare @KitchenTransNote Varchar(256)
Declare @TransactionDateStamp DateTime
DECLARE @TransactionDateStr CHAR(8)
Declare @NewChargeDayWhenMoveDelete DateTime
Declare @Allowzeroprice Bit
Declare @TransferedFromLastName varchar(50)
Declare @AddressNumber int
Declare @UserIDNumberInTrans int
Declare @CountryCode VarChar(4)
Declare @PhoneAndPayTvDiscount smallint
Declare @HotelCustomerNumberReservation int
Declare @CentralBookingType int
Declare @TABLEBOOKING bit
Declare @WareGroupType int
Declare @AddonWare bit
DECLARE @TableReferenceNumber INT
DECLARE @tmpLineNumber INT
DECLARE @IsMenuWare BIT
DECLARE @IsMenuWareDiscount BIT
DECLARE @cntTransfer INT
DECLARE @NewPieces INT
DECLARE @NewProductWareLinkNumberWhenMoveDelete INT
DECLARE @NewProductWareLinkNumberWhenMoveDelete1 INT
DECLARE @TransferToHotelCustomerNumber int
DECLARE @ReductionPercent FLOAT
DECLARE @OriginalPrice FLOAT
DECLARE @OriginalPieces INT
DECLARE @FirstGlobaltransactionNumberOnlyOnce INT

DECLARE @UseCashDesk BIT
DECLARE @LastTransactionNumber INT
DECLARE @WareType SMALLINT 

DECLARE @TranTranOrgId INT

--SELECT @UseCashDesk = CONVERT(BIT, KeyValue) FROM HotelSetup WITH (NOLOCK) WHERE Searchkey = 'FiscalPrinterSweden'
SELECT @UseCashDesk = dbo.GetHotelSetupKeyValue ('FiscalPrinterSweden', @HotelCustomerNumber)
SET @UseCashDesk = ISNULL(@UseCashDesk,0)

IF @UseCashDesk = 1 AND ISNULL(@ACashDesk, -1) <= -1
  SET @ACashDesk = 1

IF @ShowPrint = 1
  PRINT '@CountryNumber= ' + CONVERT(VARCHAR, @CountryNumber)

DECLARE @MyCountryNumber INT

IF ISNULL(@CountryNumber, 0) <= 0
BEGIN
  SELECT @MyCountryNumber = CONVERT(INT,KeyValue) FROM HotelSetup WITH (NOLOCK) WHERE SearchKey='CountryCode'
  IF @@ROWCOUNT = 0
  SELECT TOP 1 @MyCountryNumber = CountryNumber FROM Countries WITH (NOLOCK)
END
ELSE
  SET @MyCountryNumber = @CountryNumber

IF @ShowPrint = 1
  PRINT '@MyCountryNumber= ' + CONVERT(VARCHAR, @MyCountryNumber)

SELECT @CurrentDateStr = SYSTEMDATE FROM System WITH (NOLOCK)  WHERE NUMBER = 1  -- Only one record

SELECT @PhoneAndPayTvDiscount = Convert(Integer, KeyValue) FROM Hotelsetup WITH (NOLOCK)  WHERE Searchkey = 'PhoneAndPayTvDiscount'
if isnull(@PhoneAndPayTvDiscount,0)=0 SET @PhoneAndPayTvDiscount = 0

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

Select @TABLEBOOKING = Convert(Bit, Keyvalue) From HotelSetup WITH (NOLOCK) WHERE SearchKey = 'TableBookingEnabled'
if isnull(@TABLEBOOKING,0)=0 SET @TABLEBOOKING = 0

if ISNULL(@Note, '') = '' set @Note = ''

if isnull(@HotelCustomerNumber,-1) = -1 SET @HotelCustomerNumber = -1

SET @ATranRelationType = ISNULL(@ATranRelationType, 0)

if (@HotelCustomerNumber = -1) and (@CentralBookingType IN (3,7)) -- cotCentralNoLink, cotMPMS
begin
  if isnull(@PostOnReferenceNumber, 0) <> 0
  begin
    select @HotelCustomerNumber = Customer.CustomerNumber 
    from Customer WITH (nolock) 
    where HotelNumber in (select HotelNumber from ReservationMain WITH (nolock) where ReferenceNumber = @PostOnReferenceNumber)
    And CustomerTypeNumber = 7
  end

  if (@HotelCustomerNumber = -1) and (isnull(@RoomNumber,0) <> 0)
  begin
    DECLARE @cnt INT
    select @cnt = Count(Customer.CustomerNumber)
    from Customer WITH (NOLOCK)
    left outer join RoomTypes WITH (nolock) on Customer.HotelNumber = RoomTypes.HotelNumber
    INNER JOIN Rooms WITH (nolock) ON Rooms.RoomTypeNUmber = RoomTypes.RoomTypeNumber and Rooms.Number = @RoomNumber 
    where Customer.CustomerTypeNumber = 7  
    AND ISNULL(Customer.MarkAsDeleted, 0) = 0

    if @cnt = 1
      select @HotelCustomerNumber = Customer.CustomerNumber 
      from Customer WITH (NOLOCK)
      left outer join RoomTypes WITH (nolock) on Customer.HotelNumber = RoomTypes.HotelNumber
      INNER JOIN Rooms WITH (nolock) ON Rooms.RoomTypeNUmber = RoomTypes.RoomTypeNumber and Rooms.Number = @RoomNumber 
      where Customer.CustomerTypeNumber = 7  
      AND ISNULL(Customer.MarkAsDeleted, 0) = 0
    else
      RAISERROR('Error in storedprocedure <<postering>>: HotelCustomerNumber = -1 and hotel is running as a chain. Could not retrive hotel by logic',15,1)
  end

  if (@HotelCustomerNumber = -1) 
    RAISERROR('Error in storedprocedure <<postering>>: HotelCustomerNumber = -1 and hotel is running as a chain. ',15,1)
end
ELSE IF NOT @CentralBookingType IN (3,7)
  SET @HotelCustomerNumber = -1
ELSE
BEGIN
  -- what if customer/hotel is deleted
  SELECT @HotelCustomerNumber = CustomerNumber 
  FROM Customer WITH (NOLOCK)
  WHERE CustomerNumber = @HotelCustomerNumber
  AND ISNULL(MarkAsDeleted, 0) = 0
  AND HotelNumber >= 0
  
  if (@HotelCustomerNumber = -1) 
    RAISERROR('Error in storedprocedure <<postering>>: Hotel in Customer table is deleted.',15,1)
END

if isnull(@PostForDatetime,0) = 0 SET @PostForDatetime = 0
if isnull(@FirstAddressNumber,0) = 0 SET @FirstAddressNumber = 0

if @FK_DepartmentNumber > 0
begin
  -- Make sure department is not deleted
  SELECT @FK_DepartmentNumber = PK_Department FROM Departments WITH (NOLOCK) WHERE ((MarkASDeleted=0) OR (MarkASDeleted is null)) and PK_Department = @FK_DepartmentNumber
  if ISNULL(@FK_DepartmentNumber, 0) = 0 SET @FK_DepartmentNumber = 1
end
else
begin
--  SELECT TOP 1 @FK_DepartmentNumber = PK_Department FROM Departments WITH (NOLOCK) WHERE AutoCharge = 1 AND ((MarkAsDeleted=0) OR (MarkAsDeleted IS NULL))  ORDER BY SortNumber
  SELECT TOP 1 @FK_DepartmentNumber = 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 = @HotelCustomerNumber)))
  ORDER BY SortNumber

  if ISNULL(@FK_DepartmentNumber, 0) = 0
    SELECT TOP 1 @FK_DepartmentNumber = PK_Department FROM Departments WITH (NOLOCK) WHERE ((MarkASDeleted=0) OR (MarkASDeleted IS NULL)) ORDER BY SortNumber
end

IF CONVERT(INT, @PostForDatetime) < CONVERT(INT, CONVERT(DATETIME, @CurrentDateStr))
  EXEC SystemDateTime '', @PostForDatetime OUTPUT
EXEC SystemDateTime '', @RealDateTimeForTransaction OUTPUT

SET @WareGroupType = -1

DECLARE @tmpFolioNumber INT
DECLARE @tmpGlobalTransactionNumber INT
SELECT @tmpGlobalTransactionNumber = GlobalTransactionNumber, @tmpFolioNumber = FolioNumber 
FROM Transactions WITH (NOLOCK) 
WHERE Transactionnumber = @MovedTransactionNumber

IF ISNULL(@tmpGlobalTransactionNumber, 0) > 0 AND @Correction=1 AND @MovedTransactionNumber > 0
BEGIN
  DECLARE @cntmovdel INT
 
  SELECT @cntmovdel = COUNT(*) FROM Transactions WITH (NOLOCK) 
  WHERE GlobaltransactionNumber = @tmpGlobalTransactionNumber
  AND MovedDeleted = 1
  AND FolioNumber = @tmpFolioNumber
  AND ISNULL(MovedFolioNr, 0) = 0
  IF ISNULL(@cntmovdel, 0) >= 1
    RAISERROR('Error in storedprocedure <<postering>>: Transaction is already deleted.',15,1)
END

IF ISNULL(@@ERROR,0) = 0
BEGIN
EXEC WareIsMenuWare @WareNumber, @Price, 1, @IsMenuWare OUTPUT

IF @AArrangementLineNumber <= 0
  SET @AArrangementLineNumber = NULL

IF @IsMenuWare = 1 AND @Correction = 0 AND ISNULL(@MovedFolioNumber, 0) = 0
BEGIN
  EXEC GetNextNumber 'GLOBALTRANSACTIONIDENTITY', 1, @GlobalTransactionNumber OUTPUT
  EXEC PostMenuWare @WareNumber, @FK_DepartmentNumber, @GlobalTransactionNumber, @RealDateTimeForTransaction, @PostForDatetime, @UserIDNumber, @FolioNumber, @Pieces, @MyCountryNumber, @Payment, @Note, @ProductWareLinkNumber, @HotelCustomerNumber, @ChargedWithCard, @MovedFolioNumber, @TakeAccountsFromWareNumber, @Price, @ACashDesk, @WareTextOverwrite, @AArrangementLineNumber
END
ELSE 
BEGIN
  if NOT((@Correction=1) AND (@Payment = 11) AND (@DepositFollowupNumber>0))
  Begin
    if @Payment in (10,11,12) and (@WareNumber=0) -- checkin,wanted and receiveDeposit
    Begin
      Declare @DepositWareText varchar(100)
--      Select @Warenumber=Warenumber, @DepositWareText = WareName from Ware WITH (nolock) where Payment=@Payment and (MarkAsDeleted is null) order by SortNumber
      if (@CentralBookingType IN (3,7))
      BEGIN
        SELECT @Warenumber = Ware.Warenumber, @DepositWareText = Ware.WareName
        FROM Ware WITH (nolock) 
        INNER JOIN WareDepartmentsXtab wdx WITH (NOLOCK) ON wdx.WareNumber = Ware.WareNumber
          AND wdx.Type = 1 --Cashier department 
        INNER JOIN Departments d WITH (NOLOCK) ON d.PK_Department = wdx.FK_Department
        INNER JOIN Customer c WITH (NOLOCK) ON c.HotelNumber = d.HotelNumber 
          AND c.CustomerTypeNumber = 7 
          AND ISNULL(c.MarkAsDeleted, 0) = 0
          AND c.CustomerNumber = @HotelCustomerNumber
        WHERE Ware.Payment = @Payment
        AND ISNULL(Ware.MarkAsDeleted, 0) = 0 
        ORDER BY Ware.SortNumber
        
        IF ISNULL(@WareNumber, 0) = 0 
          Select @Warenumber=Warenumber, @DepositWareText = WareName from Ware WITH (nolock) where Payment=@Payment and (MarkAsDeleted is null) order by SortNumber      
      END
      ELSE
        Select @Warenumber=Warenumber, @DepositWareText = WareName from Ware WITH (nolock) where Payment=@Payment and (MarkAsDeleted is null) order by SortNumber      

      if @WareTextOverwrite = '' 
        SET @WareTextOverwrite = @DepositWareText 
    end

    if @TransferToFolioNumber<0 SET @TransferToFolioNumber = 0
    if @PostOnReferenceNumber<0 SET @PostOnReferenceNumber = 0

    IF @ShowPrint = 1
    BEGIN
      print 'warenumber'
      print @WareNumber
      print @ResultAccountNumber
    END

    if (@TakeAccountsFromWareNumber>0)
    begin
      if @Payment=0
      begin
        Declare @ChargeDiscountAs Bit

        Declare @IsTakeFromWareNumberRoomHall bit
        Select top 1 @IsTakeFromWareNumberRoomHall = Count(*) From Ware WITH (nolock) where WareNumber = @TakeAccountsFromWareNumber and WareGroupNumber in (Select WareGroupNumber From WareGroups WITH (Nolock) where Payment in (2,3) and ((markasdeleted is null) OR MarkAsDeleted='0'))

        if (@IsTakeFromWareNumberRoomHall = 0)
        begin 
          SELECT @ChargeDiscountAs=Convert(Bit,KeyValue) From Hotelsetup WITH (NOLOCK) WHERE SEARCHKEY='ChargeCustomDiscountAsWare'
          IF ISNULL(@ChargeDiscountAs,0)=0 SET @ChargeDiscountAs=0
        end
        else
        begin 
        SELECT @ChargeDiscountAs=Convert(Bit,KeyValue) From Hotelsetup WITH (NOLOCK) WHERE SEARCHKEY='ChargeDiscountAsProduct'
          IF ISNULL(@ChargeDiscountAs,1)=1 SET @ChargeDiscountAs=1
        end

        if @ChargeDiscountAs=1
        begin
          Select @WareSortNumber= SortNumber, @WareGroupNumber = WareGroupNumber, @WarePrice = Price, @WareText = WareName, @Allowzeroprice = AllowZeroPrice From Ware WITH (NOLOCK) where (WareNumber=@WareNumber)
          Select @ResultAccountNumber = ResultAccountNumber, @BalanceAccountNumber = BalanceAccountNumber, @PaymentBalanceAccountNumber = PaymentBalanceAccountNumber, @WareType = Type From Ware WITH (NOLOCK) where (WareNumber=@TakeAccountsFromWareNumber)
          Select @VATValueNumber = VatValueNumber,@VATAccountNumber=VATAccountNumber  From Accounts WITH (NOLOCK) Where Accounts.AccountNumber = @ResultAccountNumber
        end
        else 
        begin
          Select @ResultAccountNumber = ResultAccountNumber, @BalanceAccountNumber = BalanceAccountNumber, @PaymentBalanceAccountNumber = PaymentBalanceAccountNumber, @WareSortNumber= SortNumber, @WareGroupNumber = WareGroupNumber, @WarePrice = Price, @WareText = WareName, @VATAccountNumber = Accounts.VATAccountNumber, @Allowzeroprice = AllowZeroPrice, @WareType = Type From Ware WITH (NOLOCK)
          INNER JOIN Accounts WITH (NOLOCK) ON Accounts.Accountnumber = ResultAccountNumber
          where  (WareNumber=@WareNumber)
          Select @VATValueNumber = VatValueNumber From Accounts WITH (NOLOCK)
          Where Accounts.AccountNumber in (Select ResultAccountNumber  From Ware WITH (NOLOCK) where
          (WareNumber=@TakeAccountsFromWareNumber))
        end
      end
      else
      begin
        Set @VATAccountNumber = 0
        Set @VATValueNumber = 0
        Select @ResultAccountNumber = ResultAccountNumber, @BalanceAccountNumber = BalanceAccountNumber, @PaymentBalanceAccountNumber = PaymentBalanceAccountNumber, @WareSortNumber= SortNumber, @WareGroupNumber = WareGroupNumber, @WarePrice = Price, @WareText = WareName, @Allowzeroprice = AllowZeroPrice, @WareType = Type From Ware WITH (NOLOCK) 
        where WareNumber=@WareNumber
      end
    end
    else
    begin
      if @Payment=0
      begin
        Select  @WareGroupType = WareGroups.Payment, @InterfaceNumber = InterfaceNumber, @ResultAccountNumber = ResultAccountNumber, @BalanceAccountNumber = BalanceAccountNumber, 
          @PaymentBalanceAccountNumber = PaymentBalanceAccountNumber, @WareSortNumber= Ware.SortNumber, @WareGroupNumber = Ware.WareGroupNumber, @WarePrice = Price, 
          @WareText = WareName, @VATAccountNumber = Accounts.VATAccountNumber,  @VATValueNumber = Accounts.VatValueNumber, @Allowzeroprice = AllowZeroPrice, @WareType = Type
        From Ware WITH (NOLOCK) 
        INNER JOIN Accounts WITH (NOLOCK) ON Accounts.Accountnumber = ResultAccountNumber
        INNER JOIN WareGroups WITH (NOLOCK) ON WareGroups.WareGroupNumber = Ware.WareGroupNumber
        where (WareNumber=@WareNumber)
      end
      else
      begin
        Set @VATAccountNumber = 0
        Set @VATValueNumber = 0

        if @Payment = 12 AND @Pieces<0
        begin
          Select @BalanceAccountNumber = AccountNumber from Accounts WITH (NOLOCK) where AccountType = 8 AND (MarkAsDeleted is null OR MarkAsDeleted='0')
          Select @ResultAccountNumber = ResultAccountNumber, @PaymentBalanceAccountNumber = PaymentBalanceAccountNumber, @WareSortNumber= SortNumber, @WareGroupNumber = WareGroupNumber, @WarePrice = Price, @WareText = WareName, @Allowzeroprice = AllowZeroPrice, @WareType = Type From Ware WITH (NOLOCK) where WareNumber=@WareNumber
        end
        else
        begin 
          SELECT @ResultAccountNumber = ResultAccountNumber, @BalanceAccountNumber = BalanceAccountNumber, @PaymentBalanceAccountNumber = PaymentBalanceAccountNumber, @WareSortNumber= SortNumber, 
            @WareGroupNumber = WareGroupNumber, @WarePrice = Price, @WareText = WareName, @Allowzeroprice = AllowZeroPrice, @WareType = Type 
          FROM Ware WITH (NOLOCK) WHERE WareNumber=@WareNumber

          IF @Waretype = 4 --wtTransfer
            SET @PaymentBalanceAccountNumber = @ResultAccountNumber

          IF @ShowPrint = 1 
          BEGIN
            PRINT '@Waretype'
            PRINT @Waretype
            PRINT 'BalanceAccountNumber'
            PRINT @BalanceAccountNumber
            PRINT 'PaymentBalanceAccountNumber'
            PRINT @PaymentBalanceAccountNumber
          END
        end 
      end 
    end

    if IsNull(@InterfaceNumber,0)=0 SET @InterfaceNumber = 0
    if isnull(@Allowzeroprice,0)=0  SET @Allowzeroprice=0

    if @WareGroupNumber IN (SELECT WareGroupNumber FROM WareGroups WITH (NOLOCK) WHERE Payment = 5 and ISNULL(MarkAsDeleted, '0') = '0') -- provision/rabat
    begin
      SET @PostDiscount = 1
      --if  @WareSortNumber in (3,6,9) SET @PostVAT=0  -- if provision to other than dk and eu
      IF @WareType IN (12,15,18) SET @PostVAT = 0 -- if provision to other than dk and eu
    end

    if (@PostVAT = 0)
      SET @VATValueNumber=0

    exec GetVatvalueFromVATValueNumber @VATValueNumber, @VatValueWare OUTPUT 

    if @WareGroupNumber in (Select WareGroupNumber From WareGroups WITH (Nolock) where Payment in (2,3,7,8) and ISNULL(MarkAsDeleted, '0') = '0')
      SET @WareIsHallRoom = 1
    else
      SET @WareIsHallRoom = 0

    if (@Correction=1)  OR ((@MovedTransactionNumber>0) AND (@MovedFolioNumber > 0))
    begin
      if ((@Correction=1) AND (@WareIsHallRoom = 1)) OR ((@MovedTransactionNumber>0) AND (@MovedFolioNumber > 0) AND (@Pieces=0) AND (@Price=0)) -- "normal ware" + rooms/halls
        Select @ProductWareLinkNumber = isnull(ProductWareLinkNumber,0) from Transactions WITH (nolock) where Transactionnumber=@MovedTransactionNumber
      ELSE IF NOT (@WareIsHallRoom = 1 AND @ProductWareLinkNumber > 0)
        Set @ProductWareLinkNumber = 0
    end
    else if @ProductWareLinkNumber=-1
      Set @ProductWareLinkNumber = 0

    if isnull(@PackageNumber,0)=0 
      SET @PackageNumber = 0

    SET @OriginalWareText = @WareText

    if (@WareTextOverwrite>'')
      SET @WareText = @WareTextOverwrite

    if ((@Payment > 0) AND (@MovedFolioNumber<=0)) -- betaling
    begin
      if @Payment=6 -- valutta
      begin
        SELECT @ExchangeRate = CurrencySettlement From Countries WITH (NOLOCK) where (CountryNumber=@MyCountryNumber)
        SET @ExchangeRate = @ExchangeRate/100
      end
      else
        SET @ExchangeRate = 1
	  
	  IF @ExchangeRate <> 1
      SET @WareText = @WareText + ' (' + CAST(@ExchangeRate AS VARCHAR) +')'

      SET @WarePrice = @Price
    end
    else if (@Payment = 0)
    begin
      if ((@Price<>0) OR (@Allowzeroprice=1 and @Price=0))
        SET @WarePrice = @Price

      SET @ExchangeRate = 1

      SELECT @MyCountryNumber = CountryNumber From Countries WITH (NOLOCK) where (CountryNumber=@MyCountryNumber) AND MarkAsDeleted=0

      if @@RowCount = 0
      begin
        select @CountryCode = TextValue from hotelsetup WITH (nolock) where searchkey like 'CountryCode'
        SELECT @MyCountryNumber = CountryNumber From Countries WITH (NOLOCK) where (CountryCode=@CountryCode) AND MarkAsDeleted=0

        IF @@ROWCOUNT = 0 
          SELECT TOP 1 @MyCountryNumber = CountryNumber FROM Countries WITH (NOLOCK)
      end 

      IF @ShowPrint = 1
        PRINT 'Payment = 0 @MyCountryNumber='+ CONVERT (VARCHAR, @MyCountryNumber);    
    end

    if (((@RoomNumber>0) AND (@FolioNumber<=0)) OR ((@TransferToReferenceNumber>0) AND (@TransferToFolioNumber<=0)) OR (@PostOnReferenceNumber>0))
    -- der skal tages højde for splitbill
    begin
      Declare @ReferenceNumber int
      Declare @GuestNumber int

      if ((@RoomNumber>0) AND (@FolioNumber<=0))
      begin
        if @PostOnGuestNumber<=0
        begin
          SELECT Top 1 @ReferenceNumber = TRV.ReferenceNumber, @GuestNumber = TRV.GuestNumber, @SplitBillNumber = TRV.SplitBill, @HotelCustomerNumberReservation = isnull(C.CustomerNumber,-1) 
          FROM dbo.TFindReservationView TRV WITH (NOLOCK) 
            LEFT OUTER JOIN dbo.Customer C WITH (NOLOCK) ON TRV.RoomTypesHotel = C.HotelNumber AND C.HotelNumber>=0 AND C.CustomerTypeNumber = 7 -- SalesChannel
          WHERE  ((TRV.Status=5) AND ((TRV.SpecRoomNumber = @RoomNumber) OR (TRV.SideHouseNumber = @RoomNumber))) and (@HotelCustomerNumber = -1 or C.CustomerNumber = @HotelCustomerNumber)
          order by TRV.GuestNumber
          SET @PostOnGuestNumber = @GuestNumber
        end
        else
        begin
          SET @GuestNumber = @PostOnGuestNumber
          SELECT @ReferenceNumber = TRV.ReferenceNumber, @SplitBillNumber = TRV.SplitBill, @HotelCustomerNumberReservation = isnull(C.CustomerNumber,-1)
          FROM TFindReservationView TRV WITH (NOLOCK) -- ks 2/4-2002
          LEFT OUTER JOIN Customer C WITH (NOLOCK) ON TRV.RoomTypesHotel = C.HotelNumber AND C.HotelNumber>=0 AND C.CustomerTypeNumber = 7 -- SalesChannel
          WHERE ((TRV.Status=5) AND ((TRV.SpecRoomNumber = @RoomNumber) OR (TRV.SideHouseNumber = @RoomNumber))) and TRV.Guestnumber = @GuestNumber and (@HotelCustomerNumber = -1 or C.CustomerNumber = @HotelCustomerNumber)
        end

        if @HotelCustomerNumber = -1 AND @HotelCustomerNumberReservation>-1 AND @CentralBookingType IN (3,7) -- cotCentralNoLink, cotMPMS
          SET @HotelCustomerNumber = @HotelCustomerNumberReservation

        if @Note = '' SET @Note = Convert(Char, @RoomNumber)

        if isnull(@ReferenceNumber,0)=0 
          RAISERROR('Error in storedprocedure <<postering>> : Room not inhouse ',15,1)

        SET @AddressType = 0

        if IsNull(@SplitBillNumber,0)=0 SET @SplitBillNumber = 0
        exec FindFolioNumber @ReferenceNumber, @GuestNumber, @UserIDNumber, @WareNumber, @SplitBillNumber, 1, @FolioNumber OUTPUT, @AddressType OUTPUT, @FirstAddressNumber

        IF (@FirstAddressNumber > 0) and (@FirstAddressNumber > 0)
          SET @FirstAddressNumber = @FirstAddressNumber+1
      end
      else if ((@TransferToReferenceNumber>0) AND (@TransferToFolioNumber<=0))
      begin
        SET @AddressType = @TransferToAddressTypeNumber

        exec FindFolioNumber @TransferToReferenceNumber, @TransferToGuestNumber, @UserIDNumber, @WareNumber, 0, 1, @TransferToFolioNumber OUTPUT, @AddressType OUTPUT, @FirstAddressNumber

        IF (@FirstAddressNumber > 0) and (@FirstAddressNumber > 0)
          SET @FirstAddressNumber = @FirstAddressNumber+1

        SELECT @ReferenceNumber = Folios.ReferenceNumber, @GuestNumber = Folios.GuestNumber, @AddressNumber = Folios.ReservationAddressNumber, @TableNumber = CONFERENCEROOMS.Number
        FROM FOLIOS WITH (nolock) 
        LEFT OUTER JOIN FolioRestResTableChairsXTab WITH (nolock) ON FOLIOS.FolioNumber = FolioRestResTableChairsXTab.FolioNumber
        INNER JOIN CONFERENCEROOMS WITH (nolock) ON FolioRestResTableChairsXTab.TableNumber = CONFERENCEROOMS.ConferenceRoomNumber
        WHERE (Folios.FolioNumber = @FolioNumber)

        if isnull(@TableNumber,0)=0 SET @TableNumber = 0
        if isnull(@ReferenceNumber,0)=0 SET @ReferenceNumber = 0
        if isnull(@GuestNumber,-1)=-1 SET @GuestNumber = NULL
        if isnull(@AddressNumber,0)=0 SET @AddressNumber = 0

        if @AddressNumber>0 
          Select @TransferedFromLastName = LastName from ReservationAddress WITH (nolock) where Addressnumber = @AddressNumber
        else
          SET @TransferedFromLastName = ''

        if @ReferenceNumber>0
          SELECT @TransferFromRoomNumber = SpecRoomNumber  FROM TFindReservationView WITH (NOLOCK)  WHERE ReferenceNumber=@ReferenceNumber and GuestNumber=@GuestNumber
        else 
          SET @TransferFromRoomNumber = 0

        if @TableNumber>0
          SET @TransferFromTableNumber = @TableNumber
        else 
          SET @TransferFromTableNumber = 0

        if @Note = ''
        begin 
          if isnull(@TransferToReferenceNumber,0)=0 SET @TransferToReferenceNumber = 0
          if isnull(@TransferToGuestNumber,0)=0 SET @TransferToGuestNumber = 0

          if @TransferToReferenceNumber>0
          begin
            SELECT @RoomNumber = SpecRoomNumber  FROM TFindReservationView WITH (NOLOCK)  WHERE ReferenceNumber=@TransferToReferenceNumber and GuestNumber=@TransferToGuestNumber
            if @TransferToReferenceNumber>0
            SET @Note = Convert(Char, @RoomNumber)
          end 
        end 
      end
      else if (@PostOnReferenceNumber>0)
      begin
        SET @ReferenceNumber = @PostOnReferenceNumber
        SET @GuestNumber = @PostOnGuestNumber
        SET @AddressType = 0
        SET @SplitBillNumber = 0

        if @Payment = 11
        begin  
          SET @FolioNumber = 0
          Select @FolioNumber = FolioNumber from Transactions WITH (nolock) where moveddeleted=0 and depositfollowupnumber=@DepositFollowupNumber

          if @FolioNumber = 0
          begin
/*
            SELECT @SplitBillNumber = SplitBill, @HotelCustomerNumberReservation = isnull(Customer.CustomerNumber,-1) FROM TFindReservationView WITH (NOLOCK) 
            Left outer join Customer WITH (NOLOCK) ON TFindReservationView.HotelNumber = Customer.HotelNumber AND Customer.HotelNumber>=0 AND Customer.CustomerTypeNumber = 7 AND ISNULL(Customer.MarkAsDeleted, 0) = 0
            WHERE ReferenceNumber=@ReferenceNumber AND GuestNumber = @GuestNumber

            if IsNull(@SplitBillNumber,0)=0 SET @SplitBillNumber = 0
*/
            if @HotelCustomerNumber = -1 AND @HotelCustomerNumberReservation>-1 AND @CentralBookingType IN (3,7) -- cotCentralNoLink, cotMPMS
              SET @HotelCustomerNumber = @HotelCustomerNumberReservation

            Select @TempWareNumber = WareNumber from Ware WITH (nolock) where (MarkAsDeleted is null) and WareGroupNumber in (Select Waregroupnumber from waregroups WITH (nolock) where payment in (2,3)) -- 2,3 = rooms/halls

            SET @TableReferenceNumber = 0
            SELECT @tmpLineNumber = ISNULL(LineNumber, 0) FROM ReservationRoomLineXtab WITH (NOLOCK) WHERE ReferenceNumber = @ReferenceNumber

            IF ISNULL(@tmpLineNumber, 0) = 0 -- No rooms on reservation
            BEGIN          
              SELECT @tmpLineNumber = ISNULL(ReservationConfLineNumber, 0) FROM ReservationConferenceLine WITH (NOLOCK)
              WHERE ReferenceNumber = @ReferenceNumber AND ISNULL(TableBooking,0) = 0
              IF ISNULL(@tmpLineNumber, 0) = 0 -- No rooms and no halls on reservation = it's a clean tablebooking
                SELECT @TableReferenceNumber = ISNULL(ReservationConfLineNumber, 0) FROM ReservationConferenceLine WITH (NOLOCK)
                WHERE ReferenceNumber = @ReferenceNumber AND TableBooking = 1         
            END 
            exec FindFolioNumber @ReferenceNumber, @GuestNumber, @UserIDNumber, @TempWareNumber, 0, 1, @FolioNumber OUTPUT, @AddressType OUTPUT, @FirstAddressNumber, @TableReferenceNumber

            IF (@FirstAddressNumber > 0) and (@FirstAddressNumber > 0)
              SET @FirstAddressNumber = @FirstAddressNumber+1
          end
          else  
          begin 
            SELECT @ReferenceNumber = ReferenceNumber, @GuestNumber = GuestNumber  FROM Folios WITH (NOLOCK)
            WHERE (FolioNumber = @FolioNumber)
          end
        end 
        else
        begin 
          IF (@Payment <> 10) OR (ISNULL(@FolioNumber, -1) <= 0)
            exec FindFolioNumber @ReferenceNumber, @GuestNumber, @UserIDNumber, @WareNumber, 0, 1, @FolioNumber OUTPUT, @AddressType OUTPUT, @FirstAddressNumber

          IF (@FirstAddressNumber > 0) and (@FirstAddressNumber > 0)
            SET @FirstAddressNumber = @FirstAddressNumber+1

          if @Note = ''
          begin
            SELECT @RoomNumber = SpecRoomNumber, @HotelCustomerNumberReservation = isnull(Customer.CustomerNumber,-1) FROM TFindReservationView WITH (NOLOCK)  
            Left outer join Customer WITH (NOLOCK) ON TFindReservationView.HotelNumber = Customer.HotelNumber AND Customer.HotelNumber>=0 AND Customer.CustomerTypeNumber = 7 AND ISNULL(Customer.MarkAsDeleted, 0) = 0
            WHERE ReferenceNumber=@ReferenceNumber and GuestNumber=@GuestNumber

            SET @Note = Convert(Char, @RoomNumber)

            if @HotelCustomerNumber = -1 AND @HotelCustomerNumberReservation>-1 AND @CentralBookingType IN (3,7) -- cotCentralNoLink, cotMPMS
              SET @HotelCustomerNumber = @HotelCustomerNumberReservation
          end  
        end 
      end
    end
    else if ((@FolioNumber>0) and (@RoomNumber<=0))
    begin
      SELECT @ReferenceNumber = ReferenceNumber, @GuestNumber = GuestNumber  FROM Folios WITH (NOLOCK)
      WHERE (FolioNumber = @FolioNumber)
      if isnull(@ReferenceNumber,0)=0 
        SET @ReferenceNumber = 0

      if @PostOnGuestNumber>0 
        SET @GuestNumber = @PostOnGuestNumber
      else if isnull(@GuestNumber,-1)=-1 
        SET @GuestNumber = NULL

      if @Note = '' AND @ReferenceNumber>0
      begin 
        SELECT @RoomNumber = SpecRoomNumber, @HotelCustomerNumberReservation = isnull(Customer.CustomerNumber,-1) FROM TFindReservationView WITH (NOLOCK) 
        Left outer join Customer WITH (NOLOCK) ON TFindReservationView.HotelNumber = Customer.HotelNumber AND Customer.HotelNumber>=0 AND Customer.CustomerTypeNumber = 7 AND ISNULL(Customer.MarkAsDeleted, 0) = 0
        WHERE ReferenceNumber=@ReferenceNumber and GuestNumber=@GuestNumber
  
        SET @Note = Convert(Char, @RoomNumber)

        if @HotelCustomerNumber = -1 AND @HotelCustomerNumberReservation>-1 AND @CentralBookingType IN (3,7) -- cotCentralNoLink, cotMPMS
          SET @HotelCustomerNumber = @HotelCustomerNumberReservation
      end  
    end

    IF ((@Payment=12) AND (@Correction=1)) OR ((@MovedFolioNumber > 0) AND (@MovedTransactionNumber>0) AND (@WareIsHallRoom = 0))
    Begin
      IF @ReferenceNumber>0
        SELECT @ReservationStatus = Status FROM RESERVATIONS WITH (NOLOCK) WHERE ReferenceNumber=@ReferenceNumber AND GuestNumber=@GuestNumber
      else
      begin
        IF ISNULL(@DepositFollowupNumber,0) > 0 
          SELECT @NumberOfCheckinDeposit = Count(*) from TRANSACTIONS WITH (NOLOCK) WHERE DepositfollowupNumber= @DepositFollowupNumber AND Payment=10 AND (Moveddeleted=0)

        if ISNULL(@NumberOfCheckinDeposit, 0) > 0
          SET  @ReservationStatus = 5
        else
          SET  @ReservationStatus = 4
      end

      IF @ReservationStatus IN (5,6)
        SELECT @BalanceAccountNumber = AccountNumber from Accounts WITH (nolock) WHERE AccountType = 5 and (MarkAsDeleted='0' OR MarkAsDeleted is null)
    end

    if ((@Pieces>0) and (@WarePrice<0)) AND @Correction=0
      SET @Pieces = -1 * @Pieces

    SET @WarePrice = Round(ABS(@WarePrice * @Pieces),2)
    SET @VatOfWarePrice =  ISNULL(@WarePrice*(1-(1/convert(float,((@VatValueWare/100)+1)))), 0)

    if @Correction=0 AND (@MovedTransactionNumber <= 0)
    begin
      if ISNULL(@GlobalTransactionNumber, 0) <= 0
        EXEC GetNextNumber 'GLOBALTRANSACTIONIDENTITY', 1, @GlobalTransactionNumber OUTPUT
    end
    else IF ISNULL(@MovedTransactionNumber, 0) <= 0
    BEGIN
      DECLARE @tmpStr VARCHAR
      SET @tmpStr = 'Error in storedprocedure <<postering>>: Wrong value in MovedTransactionNumber. ' + CONVERT(VARCHAR, @MovedTransactionNumber)
      RAISERROR(@tmpStr,15,1)
    END
    ELSE IF ISNULL(@GlobaltransactionNumber, 0) <= 0 
      Select @GlobalTransactionNumber = GlobalTransactionNumber from Transactions WITH (Nolock) where Transactionnumber=@MovedTransactionNumber

    if IsNull(@Folionumber,0)=0 SET @FolioNumber=0
    if (@FolioNumber<1)
      RAISERROR('Error in storedprocedure <<postering>> : FolioNumber<1. Please contact Techotel !!',15,1)
  end

  if @PostDiscount = 0 AND @WareGroupType = 5 AND @WareType = 19 AND @Payment=0
    SET @PostDiscount = 1
  if @WareGroupType = 4 AND @WareSortNumber=5 AND @Payment=0
    Set @AddonWare = 1
  else
    Set @AddonWare = 0

  SET @VatValueWare = ISNULL(@VatValueWare, 0)

  if NOT((@Correction=1) AND (((@MovedTransactionNumber > 0) AND (@Payment<>5) AND (@WareIsHallRoom = 1) AND(@ProductWareLinkNumber>0)) OR (((@WareIsHallRoom = 1) AND (@ProductWareLinkNumber>0)) OR (@Payment = 11 AND @DepositFollowupNumber>0)) OR (@PostDiscount=1) or (@AddonWare = 1)) AND (@MovedFolioNumber<=0))
  begin
    if (ISNULL(@MovedFolioNumber,0) = 0) --AND (@MovedTransactionNumber<=0))
    begin
      if (@Payment=5 AND @TransferToFolioNumber<1 AND @Correction=0) AND (@AXPMSTransfer <> 1)
      BEGIN
        -- Hvis transfer og der ikke er noget folionumber at overføre til SIKKERHED skulle aldrig ske'
        RAISERROR('Error in storedprocedure <<postering>> : TransferToFolioNumber<1. Pleace contact Techotel !!',15,1)
      END
      else if (@Payment = 0)
      begin
        SET @WarePriceExVAT = (@WarePrice - @VatOfWarePrice)
        if @PostDiscount = 0
        begin
          if (@Pieces > 0)
          begin
            IF @ShowPrint = 1
              print 'Alm postering'
            IF @IsMenuWare = 1
            BEGIN
              DECLARE db_cur CURSOR FOR
                SELECT PAXadult, PAXChild1, PAXChild2, Pieces, PriceOverwrite, ShowOnBillFlag, Debit, WareNumber, TextOverwrite, AccountNumber, VATValue, FK_DepartmentNumber, Note
                FROM Transactions WITH (NOLOCK)
                WHERE GlobalTransactionNumber = @GlobalTransactionNumber
                AND MovedDeleted = 0
              OPEN db_cur
     
              FETCH NEXT FROM db_cur INTO  @PaxAdult, @PaxChild1, @PaxChild2, @NewPieces, @WarePriceExVAT, @ShowOnBillFlag, @Debit, @WareNumber, @WareText, @ResultAccountNumber, @VatValueWare, @FK_DepartmentNumber, @Note
            
              IF @@ROWCOUNT = 0
              BEGIN
                -- Debiter vare på omsætning på resultat excl moms
                INSERT INTO Transactions (ProductNumber, PackageNumber, GlobalTransactionNumber, OriginalGlobalTransactionNumber, RealDateTimeForTransaction, PAXadult, PAXChild1, PAXChild2, DateStamp, UserIDNumber, FolioNumber, Pieces, PriceOverwrite, CurrencyNumber, ShowOnBillFlag, Debit, MovedDeleted, WareNumber, TextOverwrite, Payment, AccountNumber, VATValue, FK_DepartmentNumber, Note, OriginalDate, ExchangeRateOverwrite, ProductWareLinkNumber, GuestNumber, HotelCustomerNumber, ChargedWithCard, FK_ArrangementLineNumber)
                VALUES(0, 0, @GlobalTransactionNumber, @GlobalTransactionNumber, @RealDateTimeForTransaction, @PaxAdult, @PaxChild1, @PaxChild2, @PostForDatetime, @UserIDNumber, @FolioNumber, @Pieces, @WarePriceExVAT , @MyCountryNumber, 0, 1, 0, @WareNumber, @WareText, @Payment, @ResultAccountNumber, @VatValueWare, @FK_DepartmentNumber, @Note, @PostForDatetime,@ExchangeRate, @ProductWareLinkNumber, @GuestNumber, @HotelCustomerNumber, @ChargedWithCard, @AArrangementLineNumber)
                IF @UseCashDesk = 1
                BEGIN
                  SELECT @LastTransactionNumber = @@Identity
                  EXEC TransactionsRelationInsert @LastTransactionNumber, @ACashDesk, @UserIDNumber
                END

                -- Krediter vare incl moms på balancekonto
                INSERT INTO Transactions (ProductNumber, PackageNumber, GlobalTransactionNumber, OriginalGlobalTransactionNumber, RealDateTimeForTransaction, PAXadult, PAXChild1, PAXChild2, DateStamp, UserIDNumber, FolioNumber, Pieces, PriceOverwrite, CurrencyNumber, ShowOnBillFlag, Debit, MovedDeleted, WareNumber, TextOverwrite, Payment, AccountNumber, VATValue, FK_DepartmentNumber, Note, OriginalDate, ExchangeRateOverwrite, ProductWareLinkNumber, GuestNumber,HotelCustomerNumber, ChargedWithCard, FK_ArrangementLineNumber)
                VALUES(0, 0, @GlobalTransactionNumber, @GlobalTransactionNumber, @RealDateTimeForTransaction, @PaxAdult, @PaxChild1, @PaxChild2, @PostForDatetime, @UserIDNumber, @FolioNumber, @Pieces, @WarePrice, @MyCountryNumber, 1, 0, 0, @WareNumber, @WareText, @Payment, @BalanceAccountNumber, @VatValueWare,  @FK_DepartmentNumber, @Note, @PostForDatetime, @ExchangeRate, @ProductWareLinkNumber, @GuestNumber, @HotelCustomerNumber, @ChargedWithCard, @AArrangementLineNumber)
                IF @UseCashDesk = 1
                BEGIN
                  SELECT @LastTransactionNumber = @@Identity
                  EXEC TransactionsRelationInsert @LastTransactionNumber, @ACashDesk, @UserIDNumber
                END

                INSERT INTO Transactions (ProductNumber, PackageNumber, GlobalTransactionNumber, OriginalGlobalTransactionNumber, RealDateTimeForTransaction, PAXadult, PAXChild1, PAXChild2, DateStamp, UserIDNumber, FolioNumber, Pieces, PriceOverwrite, CurrencyNumber, ShowOnBillFlag, Debit, MovedDeleted, WareNumber, TextOverwrite, Payment, AccountNumber, VATValue, FK_DepartmentNumber, Note, OriginalDate, ExchangeRateOverwrite, ProductWareLinkNumber, GuestNumber, HotelCustomerNumber, ChargedWithCard, FK_ArrangementLineNumber)
                VALUES(0, 0, @GlobalTransactionNumber, @GlobalTransactionNumber, @RealDateTimeForTransaction, @PaxAdult, @PaxChild1, @PaxChild2, @PostForDatetime, @UserIDNumber, @FolioNumber, @Pieces, @VatOfWarePrice, @MyCountryNumber, 0, 1, 0, @WareNumber, @WareText, @Payment, @VATAccountNumber, @VatValueWare,  @FK_DepartmentNumber, @Note, @PostForDatetime, @ExchangeRate, @ProductWareLinkNumber, @GuestNumber, @HotelCustomerNumber, @ChargedWithCard, @AArrangementLineNumber)
                IF @UseCashDesk = 1
                BEGIN
                  SELECT @LastTransactionNumber = @@Identity
                  EXEC TransactionsRelationInsert @LastTransactionNumber, @ACashDesk, @UserIDNumber
                END
              END
              ELSE
              BEGIN
                WHILE (@@FETCH_STATUS <> -1)
                BEGIN
                  IF @Debit = 1
                    SET @Debit = 0
                  ELSE
                    SET @Debit = 1
                  INSERT INTO Transactions (ProductNumber, PackageNumber, GlobalTransactionNumber, OriginalGlobalTransactionNumber, RealDateTimeForTransaction, PAXadult, PAXChild1, PAXChild2, DateStamp, UserIDNumber, FolioNumber, Pieces, PriceOverwrite, CurrencyNumber, ShowOnBillFlag, Debit, MovedDeleted, WareNumber, TextOverwrite, Payment, AccountNumber, VATValue, FK_DepartmentNumber, Note, OriginalDate, ExchangeRateOverwrite, ProductWareLinkNumber, GuestNumber, HotelCustomerNumber, ChargedWithCard, FK_ArrangementLineNumber)
                  VALUES(0, 0, @GlobalTransactionNumber, @GlobalTransactionNumber, @RealDateTimeForTransaction, @PaxAdult, @PaxChild1, @PaxChild2, @PostForDatetime, @UserIDNumber, @FolioNumber, @Pieces, (@WarePriceExVAT/@NewPieces*@Pieces)*-1, @MyCountryNumber, @ShowOnBillFlag, @Debit, 0, @WareNumber, @WareText, @Payment, @ResultAccountNumber, @VatValueWare, @FK_DepartmentNumber, @Note, @PostForDatetime, @ExchangeRate, @ProductWareLinkNumber, @GuestNumber, @HotelCustomerNumber, @ChargedWithCard, @AArrangementLineNumber)
                  IF @UseCashDesk = 1
                  BEGIN
                    SELECT @LastTransactionNumber = @@Identity
                    EXEC TransactionsRelationInsert @LastTransactionNumber, @ACashDesk, @UserIDNumber
                  END

                  FETCH NEXT FROM db_cur INTO  @PaxAdult, @PaxChild1, @PaxChild2, @NewPieces, @WarePriceExVAT, @ShowOnBillFlag, @Debit, @WareNumber, @WareText, @ResultAccountNumber, @VatValueWare, @FK_DepartmentNumber, @Note
                END
              END

              CLOSE db_cur
              DEALLOCATE db_cur
            END
            ELSE
            BEGIN
              -- Krediter vare på omsætning på resultat excl moms
              INSERT INTO Transactions (ProductNumber, PackageNumber, GlobalTransactionNumber, OriginalGlobalTransactionNumber, RealDateTimeForTransaction, PAXadult, PAXChild1, PAXChild2, DateStamp, UserIDNumber, FolioNumber, Pieces, PriceOverwrite, CurrencyNumber, ShowOnBillFlag, Debit, MovedDeleted, WareNumber, TextOverwrite, Payment, AccountNumber, VATValue, /*DepartmentOverwrite*/ FK_DepartmentNumber, Note, OriginalDate, ExchangeRateOverwrite, ProductWareLinkNumber, GuestNumber, HotelCustomerNumber, ChargedWithCard, FK_ArrangementLineNumber)
              VALUES(0, 0, @GlobalTransactionNumber, @GlobalTransactionNumber, @RealDateTimeForTransaction, @PaxAdult, @PaxChild1, @PaxChild2, @PostForDatetime, @UserIDNumber, @FolioNumber, @Pieces, @WarePriceExVAT, @MyCountryNumber, 0, 0, 0,@WareNumber,@WareText, @Payment, @ResultAccountNumber, @VatValueWare, /*@Department*/ @FK_DepartmentNumber, @Note, @PostForDatetime, @ExchangeRate, @ProductWareLinkNumber, @GuestNumber, @HotelCustomerNumber, @ChargedWithCard, @AArrangementLineNumber)
              IF @UseCashDesk = 1
              BEGIN
                SELECT @LastTransactionNumber = @@Identity
                EXEC TransactionsRelationInsert @LastTransactionNumber, @ACashDesk, @UserIDNumber
              END

              -- Debiter vare incl moms på balancekonto
              INSERT INTO Transactions (ProductNumber, PackageNumber, GlobalTransactionNumber, OriginalGlobalTransactionNumber, RealDateTimeForTransaction, PAXadult, PAXChild1, PAXChild2, DateStamp, UserIDNumber, FolioNumber, Pieces, PriceOverwrite, CurrencyNumber, ShowOnBillFlag, Debit, MovedDeleted, WareNumber, TextOverwrite, Payment, AccountNumber, VATValue, /*DepartmentOverwrite*/ FK_DepartmentNumber, Note, OriginalDate, ExchangeRateOverwrite, ProductWareLinkNumber, GuestNumber, HotelCustomerNumber, ChargedWithCard, FK_ArrangementLineNumber)
              VALUES(0, 0, @GlobalTransactionNumber, @GlobalTransactionNumber, @RealDateTimeForTransaction, @PaxAdult, @PaxChild1, @PaxChild2, @PostForDatetime, @UserIDNumber, @FolioNumber, @Pieces, @WarePrice, @MyCountryNumber, 1, 1, 0, @WareNumber, @WareText, @Payment, @BalanceAccountNumber, @VatValueWare, /*@Department*/ @FK_DepartmentNumber, @Note, @PostForDatetime, @ExchangeRate, @ProductWareLinkNumber, @GuestNumber, @HotelCustomerNumber, @ChargedWithCard, @AArrangementLineNumber)
              IF @UseCashDesk = 1
              BEGIN
                SELECT @LastTransactionNumber = @@Identity
                EXEC TransactionsRelationInsert @LastTransactionNumber, @ACashDesk, @UserIDNumber
              END

              -- Krediter momsen for varen på balancen (moms)
              INSERT INTO Transactions (ProductNumber, PackageNumber, GlobalTransactionNumber, OriginalGlobalTransactionNumber, RealDateTimeForTransaction, PAXadult, PAXChild1, PAXChild2, DateStamp, UserIDNumber, FolioNumber, Pieces, PriceOverwrite, CurrencyNumber, ShowOnBillFlag, Debit, MovedDeleted, WareNumber, TextOverwrite, Payment, AccountNumber, VATValue, /*DepartmentOverwrite*/ FK_DepartmentNumber, Note, OriginalDate, ExchangeRateOverwrite, ProductWareLinkNumber, GuestNumber, HotelCustomerNumber, ChargedWithCard, FK_ArrangementLineNumber)
              VALUES(0, 0, @GlobalTransactionNumber, @GlobalTransactionNumber, @RealDateTimeForTransaction, @PaxAdult, @PaxChild1, @PaxChild2, @PostForDatetime, @UserIDNumber, @FolioNumber, @Pieces, @VatOfWarePrice, @MyCountryNumber, 0, 0, 0,@WareNumber, @WareText, @Payment, @VATAccountNumber, @VatValueWare, /*@Department*/ @FK_DepartmentNumber, @Note, @PostForDatetime, @ExchangeRate, @ProductWareLinkNumber, @GuestNumber, @HotelCustomerNumber, @ChargedWithCard, @AArrangementLineNumber)
              IF @UseCashDesk = 1
              BEGIN
                SELECT @LastTransactionNumber = @@Identity
                EXEC TransactionsRelationInsert @LastTransactionNumber, @ACashDesk, @UserIDNumber
              END
            END
          end
          else -- kreditering
          if (@Pieces < 0)
          begin
            IF @ShowPrint = 1
              print 'Kreditering postering'

            update TransactionKitchenStatementXTab set Changed=1
            where TransactionNumber IN (
              SELECT TOP 1 TransactionNumber
              FROM Transactions WITH (NOLOCK)
              WHERE GlobalTransactionNumber=@GlobalTransactionNumber AND ShowOnBillFlag=1 
              ORDER BY TransactionNumber DESC
            )

            IF @IsMenuWare = 1
            BEGIN
              DECLARE db_cur CURSOR FOR
                SELECT PAXadult, PAXChild1, PAXChild2, Pieces, PriceOverwrite, ShowOnBillFlag, Debit, WareNumber, TextOverwrite, AccountNumber, VATValue, FK_DepartmentNumber, Note
                FROM Transactions WITH (NOLOCK)
                WHERE GlobalTransactionNumber = @GlobalTransactionNumber
                AND MovedDeleted = 0
              OPEN db_cur
     
              FETCH NEXT FROM db_cur INTO  @PaxAdult, @PaxChild1, @PaxChild2, @NewPieces, @WarePriceExVAT, @ShowOnBillFlag, @Debit, @WareNumber, @WareText, @ResultAccountNumber, @VatValueWare, @FK_DepartmentNumber, @Note
            
              IF @@ROWCOUNT = 0
              BEGIN
                -- Debiter vare på omsætning på resultat excl moms
                INSERT INTO Transactions (ProductNumber, PackageNumber, GlobalTransactionNumber, OriginalGlobalTransactionNumber, RealDateTimeForTransaction, PAXadult, PAXChild1, PAXChild2, DateStamp, UserIDNumber, FolioNumber, Pieces, PriceOverwrite, CurrencyNumber, ShowOnBillFlag, Debit, MovedDeleted, WareNumber, TextOverwrite, Payment, AccountNumber, VATValue, FK_DepartmentNumber, Note, OriginalDate, ExchangeRateOverwrite, ProductWareLinkNumber, GuestNumber, HotelCustomerNumber, ChargedWithCard, FK_ArrangementLineNumber)
                VALUES(0, 0, @GlobalTransactionNumber, @GlobalTransactionNumber, @RealDateTimeForTransaction, @PaxAdult, @PaxChild1, @PaxChild2, @PostForDatetime, @UserIDNumber, @FolioNumber, @Pieces, @WarePriceExVAT , @MyCountryNumber, 0, 1, 0, @WareNumber, @WareText, @Payment, @ResultAccountNumber, @VatValueWare, @FK_DepartmentNumber, @Note, @PostForDatetime,@ExchangeRate, @ProductWareLinkNumber, @GuestNumber, @HotelCustomerNumber, @ChargedWithCard, @AArrangementLineNumber)
                IF @UseCashDesk = 1
                BEGIN
                  SELECT @LastTransactionNumber = @@Identity
                  EXEC TransactionsRelationInsert @LastTransactionNumber, @ACashDesk, @UserIDNumber
                END

                -- Krediter vare incl moms på balancekonto
                INSERT INTO Transactions (ProductNumber, PackageNumber, GlobalTransactionNumber, OriginalGlobalTransactionNumber, RealDateTimeForTransaction, PAXadult, PAXChild1, PAXChild2, DateStamp, UserIDNumber, FolioNumber, Pieces, PriceOverwrite, CurrencyNumber, ShowOnBillFlag, Debit, MovedDeleted, WareNumber, TextOverwrite, Payment, AccountNumber, VATValue, FK_DepartmentNumber, Note, OriginalDate, ExchangeRateOverwrite, ProductWareLinkNumber, GuestNumber,HotelCustomerNumber, ChargedWithCard, FK_ArrangementLineNumber)
                VALUES(0, 0, @GlobalTransactionNumber, @GlobalTransactionNumber, @RealDateTimeForTransaction, @PaxAdult, @PaxChild1, @PaxChild2, @PostForDatetime, @UserIDNumber, @FolioNumber, @Pieces, @WarePrice, @MyCountryNumber, 1, 0, 0, @WareNumber, @WareText, @Payment, @BalanceAccountNumber, @VatValueWare,  @FK_DepartmentNumber, @Note, @PostForDatetime, @ExchangeRate, @ProductWareLinkNumber, @GuestNumber, @HotelCustomerNumber, @ChargedWithCard, @AArrangementLineNumber)
                IF @UseCashDesk = 1
                BEGIN
                  SELECT @LastTransactionNumber = @@Identity
                  EXEC TransactionsRelationInsert @LastTransactionNumber, @ACashDesk, @UserIDNumber
                END

                INSERT INTO Transactions (ProductNumber, PackageNumber, GlobalTransactionNumber, OriginalGlobalTransactionNumber, RealDateTimeForTransaction, PAXadult, PAXChild1, PAXChild2, DateStamp, UserIDNumber, FolioNumber, Pieces, PriceOverwrite, CurrencyNumber, ShowOnBillFlag, Debit, MovedDeleted, WareNumber, TextOverwrite, Payment, AccountNumber, VATValue, FK_DepartmentNumber, Note, OriginalDate, ExchangeRateOverwrite, ProductWareLinkNumber, GuestNumber, HotelCustomerNumber, ChargedWithCard, FK_ArrangementLineNumber)
                VALUES(0, 0, @GlobalTransactionNumber, @GlobalTransactionNumber, @RealDateTimeForTransaction, @PaxAdult, @PaxChild1, @PaxChild2, @PostForDatetime, @UserIDNumber, @FolioNumber, @Pieces, @VatOfWarePrice, @MyCountryNumber, 0, 1, 0, @WareNumber, @WareText, @Payment, @VATAccountNumber, @VatValueWare,  @FK_DepartmentNumber, @Note, @PostForDatetime, @ExchangeRate, @ProductWareLinkNumber, @GuestNumber, @HotelCustomerNumber, @ChargedWithCard, @AArrangementLineNumber)
                IF @UseCashDesk = 1
                BEGIN
                  SELECT @LastTransactionNumber = @@Identity
                  EXEC TransactionsRelationInsert @LastTransactionNumber, @ACashDesk, @UserIDNumber
                END
              END
              ELSE
              BEGIN
                WHILE (@@FETCH_STATUS <> -1)
                BEGIN
                  IF @Debit = 1
                    SET @Debit = 0
                  ELSE
                    SET @Debit = 1
                  INSERT INTO Transactions (ProductNumber, PackageNumber, GlobalTransactionNumber, OriginalGlobalTransactionNumber, RealDateTimeForTransaction, PAXadult, PAXChild1, PAXChild2, DateStamp, UserIDNumber, FolioNumber, Pieces, PriceOverwrite, CurrencyNumber, ShowOnBillFlag, Debit, MovedDeleted, WareNumber, TextOverwrite, Payment, AccountNumber, VATValue, FK_DepartmentNumber, Note, OriginalDate, ExchangeRateOverwrite, ProductWareLinkNumber, GuestNumber, HotelCustomerNumber, ChargedWithCard, FK_ArrangementLineNumber)
                  VALUES(0, 0, @GlobalTransactionNumber, @GlobalTransactionNumber, @RealDateTimeForTransaction, @PaxAdult, @PaxChild1, @PaxChild2, @PostForDatetime, @UserIDNumber, @FolioNumber, @Pieces, (@WarePriceExVAT/@NewPieces*@Pieces)*-1, @MyCountryNumber, @ShowOnBillFlag, @Debit, 0, @WareNumber, @WareText, @Payment, @ResultAccountNumber, @VatValueWare, @FK_DepartmentNumber, @Note, @PostForDatetime, @ExchangeRate, @ProductWareLinkNumber, @GuestNumber, @HotelCustomerNumber, @ChargedWithCard, @AArrangementLineNumber)
                  IF @UseCashDesk = 1
                  BEGIN
                    SELECT @LastTransactionNumber = @@Identity
                    EXEC TransactionsRelationInsert @LastTransactionNumber, @ACashDesk, @UserIDNumber
                  END

                  FETCH NEXT FROM db_cur INTO  @PaxAdult, @PaxChild1, @PaxChild2, @NewPieces, @WarePriceExVAT, @ShowOnBillFlag, @Debit, @WareNumber, @WareText, @ResultAccountNumber, @VatValueWare, @FK_DepartmentNumber, @Note
                END
              END

              CLOSE db_cur
              DEALLOCATE db_cur
            END
            ELSE
            BEGIN
              -- Debiter vare på omsætning på resultat excl moms
              INSERT INTO Transactions (ProductNumber, PackageNumber, GlobalTransactionNumber, OriginalGlobalTransactionNumber, RealDateTimeForTransaction, PAXadult, PAXChild1, PAXChild2, DateStamp, UserIDNumber, FolioNumber, Pieces, PriceOverwrite, CurrencyNumber, ShowOnBillFlag, Debit, MovedDeleted, WareNumber, TextOverwrite, Payment, AccountNumber, VATValue,  FK_DepartmentNumber, Note, OriginalDate, ExchangeRateOverwrite, ProductWareLinkNumber, GuestNumber, HotelCustomerNumber, ChargedWithCard, FK_ArrangementLineNumber)
              VALUES(0, 0, @GlobalTransactionNumber, @GlobalTransactionNumber, @RealDateTimeForTransaction, @PaxAdult, @PaxChild1, @PaxChild2, @PostForDatetime, @UserIDNumber, @FolioNumber, @Pieces, @WarePriceExVAT, @MyCountryNumber, 0, 1, 0, @WareNumber, @WareText, @Payment, @ResultAccountNumber, @VatValueWare, @FK_DepartmentNumber, @Note, @PostForDatetime,@ExchangeRate, @ProductWareLinkNumber, @GuestNumber, @HotelCustomerNumber, @ChargedWithCard, @AArrangementLineNumber)
              IF @UseCashDesk = 1
              BEGIN
                SELECT @LastTransactionNumber = @@Identity
                EXEC TransactionsRelationInsert @LastTransactionNumber, @ACashDesk, @UserIDNumber
              END

              -- Krediter vare incl moms på balancekonto
              INSERT INTO Transactions (ProductNumber, PackageNumber, GlobalTransactionNumber, OriginalGlobalTransactionNumber, RealDateTimeForTransaction, PAXadult, PAXChild1, PAXChild2, DateStamp, UserIDNumber, FolioNumber, Pieces, PriceOverwrite, CurrencyNumber, ShowOnBillFlag, Debit, MovedDeleted, WareNumber, TextOverwrite, Payment, AccountNumber, VATValue,  FK_DepartmentNumber, Note, OriginalDate, ExchangeRateOverwrite, ProductWareLinkNumber, GuestNumber,HotelCustomerNumber, ChargedWithCard, FK_ArrangementLineNumber)
              VALUES(0, 0, @GlobalTransactionNumber, @GlobalTransactionNumber, @RealDateTimeForTransaction, @PaxAdult, @PaxChild1, @PaxChild2, @PostForDatetime, @UserIDNumber, @FolioNumber, @Pieces, @WarePrice, @MyCountryNumber, 1, 0, 0, @WareNumber, @WareText, @Payment, @BalanceAccountNumber, @VatValueWare,  @FK_DepartmentNumber, @Note, @PostForDatetime, @ExchangeRate, @ProductWareLinkNumber, @GuestNumber, @HotelCustomerNumber, @ChargedWithCard, @AArrangementLineNumber)
              IF @UseCashDesk = 1
              BEGIN
                SELECT @LastTransactionNumber = @@Identity
                EXEC TransactionsRelationInsert @LastTransactionNumber, @ACashDesk, @UserIDNumber
              END

              INSERT INTO Transactions (ProductNumber, PackageNumber, GlobalTransactionNumber, OriginalGlobalTransactionNumber, RealDateTimeForTransaction, PAXadult, PAXChild1, PAXChild2, DateStamp, UserIDNumber, FolioNumber, Pieces, PriceOverwrite, CurrencyNumber, ShowOnBillFlag, Debit, MovedDeleted, WareNumber, TextOverwrite, Payment, AccountNumber, VATValue,  FK_DepartmentNumber, Note, OriginalDate, ExchangeRateOverwrite, ProductWareLinkNumber, GuestNumber, HotelCustomerNumber, ChargedWithCard, FK_ArrangementLineNumber)
              VALUES(0, 0, @GlobalTransactionNumber, @GlobalTransactionNumber, @RealDateTimeForTransaction, @PaxAdult, @PaxChild1, @PaxChild2, @PostForDatetime, @UserIDNumber, @FolioNumber, @Pieces,@VatOfWarePrice, @MyCountryNumber, 0, 1, 0,@WareNumber, @WareText, @Payment, @VATAccountNumber, @VatValueWare,  @FK_DepartmentNumber, @Note, @PostForDatetime, @ExchangeRate, @ProductWareLinkNumber, @GuestNumber, @HotelCustomerNumber, @ChargedWithCard, @AArrangementLineNumber)
              IF @UseCashDesk = 1
              BEGIN
                SELECT @LastTransactionNumber = @@Identity
                EXEC TransactionsRelationInsert @LastTransactionNumber, @ACashDesk, @UserIDNumber
              END
            END    
          end
        end
        else
        begin
          -- postering af discount/provision
          DECLARE @MenuChargeDiscountAs BIT
          SELECT @MenuChargeDiscountAs = CONVERT(BIT, KeyValue) FROM Hotelsetup WITH (NOLOCK) WHERE SEARCHKEY = 'ChargeCustomDiscountAsWare'
          
/*
          DECLARE @IsMenuWareDiscount INT
          SELECT @IsMenuWareDiscount = COUNT(*) FROM dbo.MenuWareXTab WITH (NOLOCK) WHERE MenuNumber = @TakeAccountsFromWareNumber
          
          SELECT @SumPercentage = SUM(mw.procentage)
          FROM dbo.ware w WITH (NOLOCK) 
          INNER JOIN dbo.MenuWareXTab mw WITH (NOLOCK) ON w.warenumber = mw.warenumber 
            AND mw.menunumber = @TakeAccountsFromWareNumber
*/
          EXEC WareIsMenuWare @TakeAccountsFromWareNumber, @WarePrice, @Pieces, @IsMenuWareDiscount OUTPUT
          
          IF @IsMenuWareDiscount = 1 AND @MenuChargeDiscountAs = 1
          BEGIN
            -- Menu ware
            DECLARE @MenuWareName VARCHAR(100)
            DECLARE @Menuprocentage MONEY 
            DECLARE @MenuResultAccountNumber INT
            DECLARE @MenuBalanceAccountNumber INT
            DECLARE @MenuPaymentBalanceAccountNumber INT
            DECLARE @MenuWareSortNumber INT
            DECLARE @MenuSingleWareNumber INT
            DECLARE @NewPrice MONEY
            DECLARE @MenuVATValueNumber INT
            DECLARE @MenuVATAccountNumber INT
            DECLARE @MenuVatValueWare MONEY
            DECLARE @MenuVatOfWarePrice MONEY
            DECLARE @MenuWarePriceExVAT MONEY
			DECLARE @InPercent BIT

            IF @Pieces > 0
            BEGIN
              INSERT INTO Transactions (ProductNumber, PackageNumber, GlobalTransactionNumber, OriginalGlobalTransactionNumber, RealDateTimeForTransaction, PAXadult, PAXChild1, PAXChild2, DateStamp, UserIDNumber, FolioNumber, Pieces, PriceOverwrite, CurrencyNumber, ShowOnBillFlag, Debit, MovedDeleted, WareNumber, TextOverwrite, Payment, AccountNumber, VATValue, FK_DepartmentNumber, Note, OriginalDate,ExchangeRateOverwrite,ProductWareLinkNumber,GuestNumber, HotelCustomerNumber, ChargedWithCard, FK_ArrangementLineNumber)
              VALUES(0, 0, @GlobalTransactionNumber, @GlobalTransactionNumber, @RealDateTimeForTransaction, @PaxAdult, @PaxChild1, @PaxChild2, @PostForDatetime, @UserIDNumber, @FolioNumber,@Pieces, @WarePrice, @MyCountryNumber, 1, 0, 0,@WareNumber, @WareText, @Payment, @BalanceAccountNumber, @VatValueWare, @FK_DepartmentNumber, @Note, @PostForDatetime,@ExchangeRate,@ProductWareLinkNumber, @GuestNumber, @HotelCustomerNumber, @ChargedWithCard, @AArrangementLineNumber)
              IF @UseCashDesk = 1
              BEGIN
                SELECT @LastTransactionNumber = @@Identity
                EXEC TransactionsRelationInsert @LastTransactionNumber, @ACashDesk, @UserIDNumber
              END
            END
            ELSE IF @Pieces < 0
            BEGIN
              INSERT INTO Transactions (ProductNumber, PackageNumber, GlobalTransactionNumber, OriginalGlobalTransactionNumber, RealDateTimeForTransaction, PAXadult, PAXChild1, PAXChild2, DateStamp, UserIDNumber, FolioNumber, Pieces, PriceOverwrite, CurrencyNumber, ShowOnBillFlag, Debit, MovedDeleted, WareNumber, TextOverwrite, Payment, AccountNumber, VATValue, FK_DepartmentNumber, Note, OriginalDate,ExchangeRateOverwrite,ProductWareLinkNumber,GuestNumber, HotelCustomerNumber, ChargedWithCard, FK_ArrangementLineNumber)
              VALUES(0, 0, @GlobalTransactionNumber, @GlobalTransactionNumber, @RealDateTimeForTransaction, @PaxAdult, @PaxChild1, @PaxChild2, @PostForDatetime, @UserIDNumber, @FolioNumber,@Pieces, @WarePrice, @MyCountryNumber, 1, 1, 0,@WareNumber, @WareText, @Payment, @BalanceAccountNumber, @VatValueWare, @FK_DepartmentNumber, @Note, @PostForDatetime,@ExchangeRate,@ProductWareLinkNumber, @GuestNumber, @HotelCustomerNumber, @ChargedWithCard, @AArrangementLineNumber)
              IF @UseCashDesk = 1
              BEGIN
                SELECT @LastTransactionNumber = @@Identity
                EXEC TransactionsRelationInsert @LastTransactionNumber, @ACashDesk, @UserIDNumber
              END
            END

            DECLARE #menuWareCur CURSOR static FOR
              SELECT w.warename, mw.procentage, w.ResultAccountNumber, w.BalanceAccountNumber, w.PaymentBalanceAccountNumber, w.SortNumber, w.warenumber, MenuWare.InPercent
              FROM dbo.ware w WITH (NOLOCK) 
              INNER JOIN dbo.MenuWareXTab mw WITH (NOLOCK) ON w.warenumber = mw.warenumber 
                AND mw.menunumber = @TakeAccountsFromWareNumber
                AND ISNULL(w.MarkAsDeleted , 0) = 0
			  INNER JOIN MenuWare WITH (NOLOCK) ON MenuWare.FK_MenuNumber = mw.menunumber
            OPEN #menuWareCur
            
            FETCH NEXT FROM #menuWareCur INTO @Menuwarename, @Menuprocentage, @MenuResultAccountNumber, @MenuBalanceAccountNumber, @MenuPaymentBalanceAccountNumber, @MenuWareSortNumber, @MenuSingleWareNumber, @InPercent

            WHILE (@@FETCH_STATUS <> -1)
            BEGIN
              IF @Menuprocentage > 0
              BEGIN
			    IF @InPercent = 1
                  SET @NewPrice = ((@WarePrice*@MenuProcentage)/100.0)
				ELSE
                  SET @NewPrice = @MenuProcentage
            
                SELECT @MenuVATValueNumber = VatValueNumber, @MenuVATAccountNumber = VATAccountNumber FROM Accounts WITH (NOLOCK) WHERE Accounts.AccountNumber = @MenuResultAccountNumber
                EXEC GetVatvalueFromVATValueNumber @MenuVATValueNumber, @MenuVatValueWare OUTPUT 
		
                SET @MenuVatOfWarePrice =  ISNULL(@NewPrice*(1-(1/CONVERT(FLOAT,((@MenuVatValueWare/100)+1)))), 0)
                SET @MenuWarePriceExVAT = (@NewPrice - @MenuVatOfWarePrice)

                EXEC PostDiscountLine 0, @UseCashDesk, @ACashDesk, @GlobalTransactionNumber, @RealDateTimeForTransaction, @PaxAdult, @PaxChild1, @PaxChild2, @PostForDatetime, @UserIDNumber, @FolioNumber, @Pieces, 
                  @MenuWarePriceExVAT, @NewPrice, @MenuVatOfWarePrice, @MyCountryNumber, @MenuSingleWareNumber, @MenuWareName, @Payment, @MenuResultAccountNumber, @MenuBalanceAccountNumber, @MenuVATAccountNumber, 
                  @MenuVatValueWare, @FK_DepartmentNumber, @Note, @ExchangeRate, @ProductWareLinkNumber, @GuestNumber, @HotelCustomerNumber, @ChargedWithCard
              END
              FETCH NEXT FROM #menuWareCur INTO @Menuwarename, @Menuprocentage, @MenuResultAccountNumber, @MenuBalanceAccountNumber, @MenuPaymentBalanceAccountNumber, @MenuWareSortNumber, @MenuSingleWareNumber, @InPercent
            END
            CLOSE #menuWareCur
            DEALLOCATE #menuWareCur
          END
          ELSE
          BEGIN
            EXEC PostDiscountLine 1, @UseCashDesk, @ACashDesk, @GlobalTransactionNumber, @RealDateTimeForTransaction, @PaxAdult, @PaxChild1, @PaxChild2, @PostForDatetime, @UserIDNumber, @FolioNumber, @Pieces, 
              @WarePriceExVAT, @WarePrice, @VatOfWarePrice, @MyCountryNumber, @WareNumber, @WareText, @Payment, @ResultAccountNumber, @BalanceAccountNumber, @VATAccountNumber, 
              @VatValueWare, @FK_DepartmentNumber, @Note, @ExchangeRate, @ProductWareLinkNumber, @GuestNumber, @HotelCustomerNumber, @ChargedWithCard
          END
        end
      end
      else -- payment
      begin
        Declare @TempWareText  Varchar(100)
        SET @TempWareText = @WareText
        SET @ShowOnBillFlag = 1

        if @Payment=5 -- until folios pr hotel
        begin
          select @TransferToHotelCustomerNumber = isnull(Customer.CustomerNumber,0) from Folios WITH (nolock)
          Left outer join Reservations WITH (nolock) on Reservations.Referencenumber=Folios.Referencenumber and Reservations.GuestNumber = Folios.GuestNumber
          Left outer join RESERVATIONMAIN WITH (nolock) on RESERVATIONMAIN.ReferenceNumber = Reservations.Referencenumber
          Left outer join Customer WITH (NOLOCK) ON RESERVATIONMAIN.HotelNumber = Customer.HotelNumber AND Customer.HotelNumber>=0 AND Customer.CustomerTypeNumber = 7 AND ISNULL(Customer.MarkAsDeleted, 0) = 0
          Where Folios.Folionumber = @TransferToFolioNumber

          if isnull(@TransferToHotelCustomerNumber,0) = 0 SET @TransferToHotelCustomerNumber = 0 -- no record maby allways a record

          if @TransferToHotelCustomerNumber = 0
            SET @TransferToHotelCustomerNumber = @HotelCustomerNumber
        end 

        DECLARE @SeparateEconomyByStaffDep BIT 
        DECLARE @tmpDepartment INT

        SELECT @SeparateEconomyByStaffDep = CONVERT(BIT, KeyValue) FROM HotelSetup WITH (NOLOCK) WHERE SearchKey = 'SeparateEconomyByStaffDep'
        IF ISNULL(@SeparateEconomyByStaffDep, 0) = 0 SET @SeparateEconomyByStaffDep = 0

        if (@Pieces > 0)
        begin
          if @Payment=5
          begin
            IF @ShowPrint = 1 
            BEGIN
              PRINT 'BalanceAccountNumber'
              PRINT @BalanceAccountNumber
              PRINT 'PaymentBalanceAccountNumber'
              PRINT @PaymentBalanceAccountNumber
            END

            IF @Waretype = 4 --wtTransfer  --KJ20060607
              EXEC PosteringTransferAsWare @GlobalTransactionNumber, @RealDateTimeForTransaction, @PaxAdult, @PaxChild1, @PaxChild2, @UserIDNumber, @FolioNumber, @Pieces, @WarePrice, @MyCountryNumber, @WareNumber, @WareText, @BalanceAccountNumber, /*@Department*/ @FK_DepartmentNumber, @Note, @PostForDatetime, @ExchangeRate, @ProductWareLinkNumber, @GuestNumber, @HotelCustomerNumber, @ChargedWithCard, @AccountType, @OriginalWareText, @TransferFromRoomNumber, @TransferFromTableNumber, @ReferenceNumber, @TransferedFromLastName, @RoomNumber, @TransferToFolioNumber, @TransferToGuestNumber, @PaymentBalanceAccountNumber, @TransferToHotelCustomerNumber, 0, @ACashDesk
            ELSE
            BEGIN
              IF @ShowPrint = 1
                PRINT 'WareType<>4' 

              -- Krediter betaling på balanceaccount
              INSERT INTO Transactions (ProductNumber, PackageNumber, GlobalTransactionNumber, OriginalGlobalTransactionNumber, RealDateTimeForTransaction, PAXadult, PAXChild1, PAXChild2, DateStamp, UserIDNumber, FolioNumber, Pieces, PriceOverwrite, CurrencyNumber, ShowOnBillFlag, Debit, MovedDeleted, WareNumber, TextOverwrite, Payment, AccountNumber, VATValue, /*DepartmentOverwrite*/ FK_DepartmentNumber, Note, OriginalDate, ExchangeRateOverwrite, ProductWareLinkNumber, GuestNumber, AutoReceivedPayment, HotelCustomerNumber, ChargedWithCard, FK_ArrangementLineNumber)
              VALUES(0, 0, @GlobalTransactionNumber, @GlobalTransactionNumber, @RealDateTimeForTransaction, @PaxAdult, @PaxChild1, @PaxChild2, @RealDateTimeForTransaction, @UserIDNumber, @FolioNumber, @Pieces, @WarePrice, @MyCountryNumber, 1, 0, 0, @WareNumber, @WareText, @Payment, @BalanceAccountNumber, 0, /*@Department*/ @FK_DepartmentNumber, @Note, @PostForDatetime, @ExchangeRate ,@ProductWareLinkNumber, @GuestNumber, 0, @HotelCustomerNumber, @ChargedWithCard, @AArrangementLineNumber)
              IF @UseCashDesk = 1
              BEGIN
                SELECT @LastTransactionNumber = @@Identity
                EXEC TransactionsRelationInsert @LastTransactionNumber, @ACashDesk, @UserIDNumber
              END

              INSERT INTO Transactions (ProductNumber, PackageNumber, GlobalTransactionNumber, OriginalGlobalTransactionNumber, RealDateTimeForTransaction, PAXadult, PAXChild1, PAXChild2, DateStamp, UserIDNumber, FolioNumber, Pieces, PriceOverwrite, CurrencyNumber, ShowOnBillFlag, Debit, MovedDeleted, WareNumber, TextOverwrite, Payment, AccountNumber, VATValue, /*DepartmentOverwrite*/ FK_DepartmentNumber, Note, OriginalDate, ExchangeRateOverwrite, ProductWareLinkNumber, GuestNumber, AutoReceivedPayment, HotelCustomerNumber, ChargedWithCard, FK_ArrangementLineNumber)
              VALUES(0, 0, @GlobalTransactionNumber, @GlobalTransactionNumber, @RealDateTimeForTransaction, @PaxAdult, @PaxChild1, @PaxChild2, @RealDateTimeForTransaction, @UserIDNumber, @FolioNumber, @Pieces, @WarePrice, @MyCountryNumber, 0, 1, 0, @WareNumber, @WareText, @Payment, @PaymentBalanceAccountNumber, 0, /*@Department*/ @FK_DepartmentNumber, @Note, @PostForDatetime, @ExchangeRate, @ProductWareLinkNumber, @GuestNumber, 0, @HotelCustomerNumber, @ChargedWithCard, @AArrangementLineNumber)
              IF @UseCashDesk = 1
              BEGIN
                SELECT @LastTransactionNumber = @@Identity
                EXEC TransactionsRelationInsert @LastTransactionNumber, @ACashDesk, @UserIDNumber
              END

              IF @AXPMSTransfer <> 1 -- only post on "FROM" folio. The "TO" folio is posted via Interface
              BEGIN 
                SET @WareText = @OriginalWareText
                if (@TransferFromRoomNumber>0) or (@TransferFromTableNumber>0)
                begin
                  if (@TransferFromRoomNumber>0)
                    SET @WareText = @WareText + ' from room '+Convert(varchar,@TransferFromRoomNumber)
                  else if (@TransferFromTableNumber>0)
                    SET @WareText = @WareText + ' table '+Convert(varchar,@TransferFromTableNumber) + ' (' + Convert(varchar,@FolioNumber) + ')'
                end
                else if @ReferenceNumber>0
                begin
                  if @RoomNumber>0
                    SET @WareText = @WareText + ' to room '+Convert(varchar,@RoomNumber)
                  else
                    SET @WareText = @WareText + ' to ref. '+Convert(varchar,@ReferenceNumber)+ '/ ' +Convert(varchar,@GuestNumber)
                  if @TransferedFromLastName<>''
                    SET @WareText = @WareText +  ', '   + @TransferedFromLastName
                end
                else if ((@FolioNumber>0) AND (@ReferenceNumber=0 ))
                begin
                  SET @WareText = @WareText + ' from folio '+Convert(varchar,@FolioNumber)

                  if @TransferedFromLastName<>''
                    SET @WareText = @WareText +  ', '  + @TransferedFromLastName
                end

                if @TransferToFolioNumber<=0  SET @TransferToFolioNumber = @FolioNumber

                IF @SeparateEconomyByStaffDep = 1
                BEGIN
                  -- Get department from DerpartmentService from the ware, and use the autoDay user
                  SET @tmpDepartment = @FK_DepartmentNumber 

                  SELECT TOP 1 @FK_DepartmentNumber = wdXTab.FK_Department
                  FROM WareDepartmentsXTab wdXTab WITH (NOLOCK) 
                  INNER JOIN Departments d WITH (NOLOCK) ON d.PK_Department = wdXTab.FK_Department AND wdXTab.Type = 2 --DepartmentService
                  WHERE WareNumber = @WareNumber
                  AND ((@CentralBookingType NOT IN (3,7)) OR (d.HotelNumber IN (SELECT HotelNumber FROM Customer WITH (NOLOCK) WHERE CustomerTypeNumber = 7 AND CustomerNumber = @HotelCustomerNumber)))
                END 

                -- Debiter vare incl moms på balancekonto
                --SET @GlobalTransactionNumber=@GlobalTransactionNumber+1
                EXEC GetNextNumber 'GLOBALTRANSACTIONIDENTITY', 1, @GlobalTransactionNumber OUTPUT

                INSERT INTO Transactions (ProductNumber, PackageNumber, GlobalTransactionNumber, OriginalGlobalTransactionNumber, RealDateTimeForTransaction, PAXadult, PAXChild1, PAXChild2, DateStamp, UserIDNumber, FolioNumber, Pieces, PriceOverwrite, CurrencyNumber, ShowOnBillFlag, Debit, MovedDeleted, WareNumber, TextOverwrite, Payment, AccountNumber, VATValue, /*DepartmentOverwrite*/ FK_DepartmentNumber, Note, OriginalDate,ExchangeRateOverwrite,ProductWareLinkNumber,GuestNumber, AutoReceivedPayment, HotelCustomerNumber, ChargedWithCard, FK_ArrangementLineNumber)
                VALUES(0, 0, @GlobalTransactionNumber, @GlobalTransactionNumber, @RealDateTimeForTransaction, @PaxAdult, @PaxChild1, @PaxChild2, @RealDateTimeForTransaction, @UserIDNumber, @TransferToFolioNumber, @Pieces, @WarePrice, @MyCountryNumber, 1,1, 0,@WareNumber, @WareText, @Payment, @BalanceAccountNumber, 0, /*@Department*/ @FK_DepartmentNumber, @Note, @PostForDatetime,@ExchangeRate,@ProductWareLinkNumber, /*@GuestNumber*/ @TransferToGuestNumber, 0, @TransferToHotelCustomerNumber, @ChargedWithCard, @AArrangementLineNumber)
                IF @UseCashDesk = 1
                BEGIN
                  SELECT @LastTransactionNumber = @@Identity
                  EXEC TransactionsRelationInsert @LastTransactionNumber, @ACashDesk, @UserIDNumber
                END

                INSERT INTO Transactions (ProductNumber, PackageNumber, GlobalTransactionNumber, OriginalGlobalTransactionNumber, RealDateTimeForTransaction, PAXadult, PAXChild1, PAXChild2, DateStamp, UserIDNumber, FolioNumber, Pieces, PriceOverwrite, CurrencyNumber, ShowOnBillFlag, Debit, MovedDeleted, WareNumber, TextOverwrite, Payment, AccountNumber, VATValue, /*DepartmentOverwrite*/ FK_DepartmentNumber, Note, OriginalDate,ExchangeRateOverwrite,ProductWareLinkNumber,GuestNumber, AutoReceivedPayment, HotelCustomerNumber, ChargedWithCard, FK_ArrangementLineNumber)
                VALUES(0, 0, @GlobalTransactionNumber, @GlobalTransactionNumber, @RealDateTimeForTransaction, @PaxAdult, @PaxChild1, @PaxChild2, @RealDateTimeForTransaction, @UserIDNumber, @TransferToFolioNumber, @Pieces, @WarePrice, @MyCountryNumber, 0,0, 0,@WareNumber, @WareText, @Payment, @PaymentBalanceAccountNumber, 0, /*@Department*/ @FK_DepartmentNumber, @Note, @PostForDatetime,@ExchangeRate,@ProductWareLinkNumber, /*@GuestNumber*/ @TransferToGuestNumber, 0, @TransferToHotelCustomerNumber, @ChargedWithCard, @AArrangementLineNumber)
                IF @UseCashDesk = 1
                BEGIN
                  SELECT @LastTransactionNumber = @@Identity
                  EXEC TransactionsRelationInsert @LastTransactionNumber, @ACashDesk, @UserIDNumber
                END

                IF @SeparateEconomyByStaffDep = 1
                  SET @FK_DepartmentNumber = @tmpDepartment 
              END
            end
          END
          else
          begin
            if @Payment=12 -- Modtaget Depositum        
            Begin
              Declare @FollowupNumber int
              Declare @FollowupDepositAmount money
              Declare @FollowupDepositNote VarChar(150)
              Declare @DepositPieces Smallint
              Declare @DepositDifference Money

              if @DepositFollowupNumber>0
              begin
                Select TOP 1
                  @FollowupNumber = Followup.FollowupNumber,
                  @FollowupDepositAmount = Followup.DepositAmount,
                  @FollowupDepositNote = Followup.Note           
                From Followup WITH (nolock) 
                Where Followup.FollowupNumber = @DepositFollowupNumber
              end
              else
              begin
                SET @FollowupNumber = @DepositFollowupNumber
                SET @FollowupDepositAmount = 0
                SET @FollowupDepositNote = @WareTextOverwrite
              end

              if @@ROWCOUNT>0 OR @FollowupNumber<=0
              begin
                SET @DepositFollowupNumber = @FollowupNumber
                if @FollowupNumber>0
                begin 
                  Update Followup SET State = 3, CompletedDate = @RealDateTimeForTransaction, CompletedBy = @UserIDNumber
                  Where Followupnumber = @FollowupNumber            
                end 

                SET @DepositDifference = @WarePrice - @FollowupDepositAmount

                if @DepositDifference <> 0
                begin
                  Declare @WantedDepositWareNumber int
                  Declare @WantedDepositBalanceAccountNumber int
                  Declare @WantedDepositPaymentBalanceAccountNumber int

                  Select
                    @WantedDepositWareNumber = WareNumber,
                    @WantedDepositBalanceAccountNumber  = BalanceAccountNumber,
                    @WantedDepositPaymentBalanceAccountNumber = PaymentBalanceAccountNumber
                  from Ware WITH (nolock) where Payment=11 AND (MarkAsDeleted is null)

                  if @DepositDifference>0 
                  begin
                    SET @DepositPieces = 1

                    INSERT INTO Transactions (ProductNumber, PackageNumber, GlobalTransactionNumber, OriginalGlobalTransactionNumber, RealDateTimeForTransaction, PAXadult, PAXChild1, PAXChild2, DateStamp, UserIDNumber, FolioNumber, Pieces, PriceOverwrite, CurrencyNumber, ShowOnBillFlag, Debit, MovedDeleted, WareNumber, TextOverwrite, Payment, AccountNumber, VATValue, /*DepartmentOverwrite*/ FK_DepartmentNumber, Note, OriginalDate,ExchangeRateOverwrite,ProductWareLinkNumber,DepositFollowupNumber,GuestNumber, AutoReceivedPayment, HotelCustomerNumber, ChargedWithCard, FK_ArrangementLineNumber)
                    VALUES(0, 0, @GlobalTransactionNumber, @GlobalTransactionNumber, @RealDateTimeForTransaction, @PaxAdult, @PaxChild1, @PaxChild2,  @RealDateTimeForTransaction, @UserIDNumber,@FolioNumber,@DepositPieces, @DepositDifference, @MyCountryNumber, 0, 1, 0,@WantedDepositWareNumber, @FollowupDepositNote, 11, @WantedDepositBalanceAccountNumber,0, /*@Department*/ @FK_DepartmentNumber, @Note, @PostForDatetime,@ExchangeRate,@ProductWareLinkNumber,@DepositFollowupNumber,@GuestNumber, @AutoReceivedPayment, @HotelCustomerNumber, @ChargedWithCard, @AArrangementLineNumber)
                    IF @UseCashDesk = 1
                    BEGIN
                      SELECT @LastTransactionNumber = @@Identity
                      EXEC TransactionsRelationInsert @LastTransactionNumber, @ACashDesk, @UserIDNumber
                    END

                    INSERT INTO Transactions (ProductNumber, PackageNumber, GlobalTransactionNumber, OriginalGlobalTransactionNumber, RealDateTimeForTransaction, PAXadult, PAXChild1, PAXChild2, DateStamp, UserIDNumber, FolioNumber, Pieces, PriceOverwrite, CurrencyNumber, ShowOnBillFlag, Debit, MovedDeleted, WareNumber, TextOverwrite, Payment, AccountNumber, VATValue, /*DepartmentOverwrite*/ FK_DepartmentNumber, Note, OriginalDate,ExchangeRateOverwrite,ProductWareLinkNumber,DepositFollowupNumber,GuestNumber, AutoReceivedPayment, HotelCustomerNumber, ChargedWithCard, FK_ArrangementLineNumber)
                    VALUES(0, 0, @GlobalTransactionNumber, @GlobalTransactionNumber, @RealDateTimeForTransaction, @PaxAdult, @PaxChild1, @PaxChild2, @RealDateTimeForTransaction, @UserIDNumber, @FolioNumber,@DepositPieces,  @DepositDifference, @MyCountryNumber, 0, 0, 0, @WantedDepositWareNumber, @FollowupDepositNote, 11, @WantedDepositPaymentBalanceAccountNumber, 0, /*@Department*/ @FK_DepartmentNumber, @Note, @PostForDatetime,@ExchangeRate,@ProductWareLinkNumber,@DepositFollowupNumber,@GuestNumber, @AutoReceivedPayment, @HotelCustomerNumber, @ChargedWithCard, @AArrangementLineNumber)
                    IF @UseCashDesk = 1
                    BEGIN
                      SELECT @LastTransactionNumber = @@Identity
                      EXEC TransactionsRelationInsert @LastTransactionNumber, @ACashDesk, @UserIDNumber
                    END
                  end
                  else
                  begin
                    SET @DepositPieces = -1
                    SET @DepositDifference = ABS(@DepositDifference)

                    INSERT INTO Transactions (ProductNumber, PackageNumber, GlobalTransactionNumber, OriginalGlobalTransactionNumber, RealDateTimeForTransaction, PAXadult, PAXChild1, PAXChild2, DateStamp, UserIDNumber, FolioNumber, Pieces, PriceOverwrite, CurrencyNumber, ShowOnBillFlag, Debit, MovedDeleted, WareNumber, TextOverwrite, Payment, AccountNumber, VATValue, /*DepartmentOverwrite*/ FK_DepartmentNumber, Note, OriginalDate,ExchangeRateOverwrite,ProductWareLinkNumber,DepositFollowupNumber,GuestNumber, AutoReceivedPayment, HotelCustomerNumber, ChargedWithCard, FK_ArrangementLineNumber)
                    VALUES(0, 0, @GlobalTransactionNumber, @GlobalTransactionNumber, @RealDateTimeForTransaction, @PaxAdult, @PaxChild1, @PaxChild2,  @RealDateTimeForTransaction, @UserIDNumber,@FolioNumber,@DepositPieces, @DepositDifference, @MyCountryNumber, 0, 0, 0,@WantedDepositWareNumber, @FollowupDepositNote, 11, @WantedDepositBalanceAccountNumber,0, /*@Department*/ @FK_DepartmentNumber, @Note, @PostForDatetime,@ExchangeRate,@ProductWareLinkNumber,@DepositFollowupNumber,@GuestNumber, @AutoReceivedPayment, @HotelCustomerNumber, @ChargedWithCard, @AArrangementLineNumber)
                    IF @UseCashDesk = 1
                    BEGIN
                      SELECT @LastTransactionNumber = @@Identity
                      EXEC TransactionsRelationInsert @LastTransactionNumber, @ACashDesk, @UserIDNumber
                    END

                    INSERT INTO Transactions (ProductNumber, PackageNumber, GlobalTransactionNumber, OriginalGlobalTransactionNumber, RealDateTimeForTransaction, PAXadult, PAXChild1, PAXChild2, DateStamp, UserIDNumber, FolioNumber, Pieces, PriceOverwrite, CurrencyNumber, ShowOnBillFlag, Debit, MovedDeleted, WareNumber, TextOverwrite, Payment, AccountNumber, VATValue, /*DepartmentOverwrite*/ FK_DepartmentNumber, Note, OriginalDate,ExchangeRateOverwrite,ProductWareLinkNumber,DepositFollowupNumber,GuestNumber, AutoReceivedPayment, HotelCustomerNumber, ChargedWithCard, FK_ArrangementLineNumber)
                    VALUES(0, 0, @GlobalTransactionNumber, @GlobalTransactionNumber, @RealDateTimeForTransaction, @PaxAdult, @PaxChild1, @PaxChild2, @RealDateTimeForTransaction, @UserIDNumber, @FolioNumber,@DepositPieces,  @DepositDifference, @MyCountryNumber, 0, 1, 0, @WantedDepositWareNumber, @FollowupDepositNote, 11, @WantedDepositPaymentBalanceAccountNumber, 0, /*@Department*/ @FK_DepartmentNumber, @Note, @PostForDatetime,@ExchangeRate,@ProductWareLinkNumber,@DepositFollowupNumber, @GuestNumber, @AutoReceivedPayment, @HotelCustomerNumber, @ChargedWithCard, @AArrangementLineNumber)
                    IF @UseCashDesk = 1
                    BEGIN
                      SELECT @LastTransactionNumber = @@Identity
                      EXEC TransactionsRelationInsert @LastTransactionNumber, @ACashDesk, @UserIDNumber
                    END
                  end      

                  --SET @GlobalTransactionNumber=@GlobalTransactionNumber+1
                  EXEC GetNextNumber 'GLOBALTRANSACTIONIDENTITY', 1, @GlobalTransactionNumber OUTPUT
                end
              end
            end

            if @Payment = 11 -- wanted deposit
              SET @Debit = 1
            else
              SET @Debit = 0

            IF @Correction = 1
              SELECT TOP 1 @ExchangeRate = ExchangeRateOverwrite, @MyCountryNumber = CurrencyNumber FROM Transactions WITH (NOLOCK) WHERE GlobalTransactionNumber = @GlobalTransactionNumber

            -- Krediter betaling på balanceaccount
            INSERT INTO Transactions (ProductNumber, PackageNumber, GlobalTransactionNumber, OriginalGlobalTransactionNumber, RealDateTimeForTransaction, PAXadult, PAXChild1, PAXChild2, DateStamp, UserIDNumber, FolioNumber, Pieces, PriceOverwrite, CurrencyNumber, ShowOnBillFlag, Debit, MovedDeleted, WareNumber, TextOverwrite, Payment, AccountNumber, VATValue, /*DepartmentOverwrite*/ FK_DepartmentNumber, Note, OriginalDate,ExchangeRateOverwrite,ProductWareLinkNumber,DepositFollowupNumber,GuestNumber, AutoReceivedPayment, HotelCustomerNumber, ChargedWithCard, FK_ArrangementLineNumber)
            VALUES(0, 0, @GlobalTransactionNumber, @GlobalTransactionNumber, @RealDateTimeForTransaction, @PaxAdult, @PaxChild1, @PaxChild2,  @RealDateTimeForTransaction, @UserIDNumber,@FolioNumber,@Pieces, @WarePrice, @MyCountryNumber, 0, @Debit, 0,@WareNumber,@WareText, @Payment, @BalanceAccountNumber,0, /*@Department*/ @FK_DepartmentNumber, @Note, @PostForDatetime,@ExchangeRate,@ProductWareLinkNumber,@DepositFollowupNumber, @GuestNumber, @AutoReceivedPayment, @HotelCustomerNumber, @ChargedWithCard, @AArrangementLineNumber)
            IF @UseCashDesk = 1
            BEGIN
              SELECT @LastTransactionNumber = @@Identity
              EXEC TransactionsRelationInsert @LastTransactionNumber, @ACashDesk, @UserIDNumber
            END

            if @Payment = 11 -- wanted deposit
            begin
              SET @Debit = 0
              SET @ShowOnBillFlag = 0
            end 
            else
            begin
              SET @Debit = 1
              if @Payment = 10 -- InhouseDeposit
                SET @ShowOnBillFlag = 0          
            end

            INSERT INTO Transactions (ProductNumber, PackageNumber, GlobalTransactionNumber, OriginalGlobalTransactionNumber, RealDateTimeForTransaction, PAXadult, PAXChild1, PAXChild2, DateStamp, UserIDNumber, FolioNumber, Pieces, PriceOverwrite, CurrencyNumber, ShowOnBillFlag, Debit, MovedDeleted, WareNumber, TextOverwrite, Payment, AccountNumber, VATValue, /*DepartmentOverwrite*/ FK_DepartmentNumber, Note, OriginalDate,ExchangeRateOverwrite,ProductWareLinkNumber,DepositFollowupNumber,GuestNumber, AutoReceivedPayment, HotelCustomerNumber, ChargedWithCard, FK_ArrangementLineNumber)
            VALUES(0, 0, @GlobalTransactionNumber, @GlobalTransactionNumber, @RealDateTimeForTransaction, @PaxAdult, @PaxChild1, @PaxChild2, @RealDateTimeForTransaction, @UserIDNumber, @FolioNumber,@Pieces, @WarePrice, @MyCountryNumber, @ShowOnBillFlag, @Debit, 0,@WareNumber, @WareText, @Payment, @PaymentBalanceAccountNumber, 0, /*@Department*/ @FK_DepartmentNumber, @Note, @PostForDatetime,@ExchangeRate,@ProductWareLinkNumber,@DepositFollowupNumber, @GuestNumber, @AutoReceivedPayment, @HotelCustomerNumber, @ChargedWithCard, @AArrangementLineNumber)
            IF @UseCashDesk = 1
            BEGIN
              SELECT @LastTransactionNumber = @@Identity
              EXEC TransactionsRelationInsert @LastTransactionNumber, @ACashDesk, @UserIDNumber
            END
          end
        end
        else if (@Pieces < 0)
        begin
          if @Payment=5
          begin
            IF @Waretype = 4 --wtTransfer  --KJ20070123
              EXEC PosteringTransferAsWare @GlobalTransactionNumber, @RealDateTimeForTransaction, @PaxAdult, @PaxChild1, @PaxChild2, @UserIDNumber, @FolioNumber, @Pieces, @WarePrice, @MyCountryNumber, @WareNumber, @WareText, @BalanceAccountNumber, /*@Department*/ @FK_DepartmentNumber, @Note, @PostForDatetime, @ExchangeRate, @ProductWareLinkNumber, @GuestNumber, @HotelCustomerNumber, @ChargedWithCard, @AccountType, @OriginalWareText, @TransferFromRoomNumber, @TransferFromTableNumber, @ReferenceNumber, @TransferedFromLastName, @RoomNumber, @TransferToFolioNumber, @TransferToGuestNumber, @PaymentBalanceAccountNumber, @TransferToHotelCustomerNumber, 1, @ACashDesk
            ELSE
            BEGIN
              SET @WareText = @TempWareText

              -- Debiter betaling på balanceaccount
              INSERT INTO Transactions (ProductNumber, PackageNumber, GlobalTransactionNumber, OriginalGlobalTransactionNumber, RealDateTimeForTransaction, PAXadult, PAXChild1, PAXChild2, DateStamp, UserIDNumber, FolioNumber, Pieces, PriceOverwrite, CurrencyNumber, ShowOnBillFlag, Debit, MovedDeleted, WareNumber, TextOverwrite, Payment, AccountNumber, VATValue, /*DepartmentOverwrite*/ FK_DepartmentNumber, Note, OriginalDate,ExchangeRateOverwrite,ProductWareLinkNumber,GuestNumber, AutoReceivedPayment, HotelCustomerNumber, ChargedWithCard, FK_ArrangementLineNumber)
              VALUES(0, 0, @GlobalTransactionNumber, @GlobalTransactionNumber, @RealDateTimeForTransaction, @PaxAdult, @PaxChild1, @PaxChild2,  @RealDateTimeForTransaction, @UserIDNumber,@FolioNumber,@Pieces, @WarePrice, @MyCountryNumber, 1, 1, 0,@WareNumber,@WareText, @Payment, @BalanceAccountNumber,0, /*@Department*/ @FK_DepartmentNumber, @Note, @PostForDatetime,@ExchangeRate,@ProductWareLinkNumber, @GuestNumber, 0, @HotelCustomerNumber, @ChargedWithCard, @AArrangementLineNumber)
              IF @UseCashDesk = 1
              BEGIN
                SELECT @LastTransactionNumber = @@Identity
                EXEC TransactionsRelationInsert @LastTransactionNumber, @ACashDesk, @UserIDNumber
              END

              INSERT INTO Transactions (ProductNumber, PackageNumber, GlobalTransactionNumber, OriginalGlobalTransactionNumber, RealDateTimeForTransaction, PAXadult, PAXChild1, PAXChild2, DateStamp, UserIDNumber, FolioNumber, Pieces, PriceOverwrite, CurrencyNumber, ShowOnBillFlag, Debit, MovedDeleted, WareNumber, TextOverwrite, Payment, AccountNumber, VATValue, /*DepartmentOverwrite*/ FK_DepartmentNumber, Note, OriginalDate,ExchangeRateOverwrite,ProductWareLinkNumber,GuestNumber, AutoReceivedPayment, HotelCustomerNumber, ChargedWithCard, FK_ArrangementLineNumber)
              VALUES(0, 0, @GlobalTransactionNumber, @GlobalTransactionNumber, @RealDateTimeForTransaction, @PaxAdult, @PaxChild1, @PaxChild2,  @RealDateTimeForTransaction, @UserIDNumber,@FolioNumber,@Pieces, @WarePrice, @MyCountryNumber, 0, 0, 0,@WareNumber,@WareText, @Payment, @PaymentBalanceAccountNumber,0, /*@Department*/ @FK_DepartmentNumber, @Note, @PostForDatetime,@ExchangeRate,@ProductWareLinkNumber, @GuestNumber, 0, @HotelCustomerNumber, @ChargedWithCard, @AArrangementLineNumber)
              IF @UseCashDesk = 1
              BEGIN
                SELECT @LastTransactionNumber = @@Identity
                EXEC TransactionsRelationInsert @LastTransactionNumber, @ACashDesk, @UserIDNumber
              END
          
              IF @AXPMSTransfer <> 1 -- only post on "FROM" folio. The "TO" folio is posted via Interface
              BEGIN 
                SET @WareText = @OriginalWareText

                if @TransferFromRoomNumber>0
                  SET @WareText = @WareText + ' from room '+Convert(varchar,@TransferFromRoomNumber)
                else if (@TransferFromTableNumber>0)
                  SET @WareText = @WareText + ' table '+Convert(varchar,@TransferFromTableNumber) + ' (' + Convert(varchar,@FolioNumber) + ')'
                else if @ReferenceNumber>0
                begin
                  if @RoomNumber>0
                    SET @WareText = @WareText + ' to room '+Convert(varchar,@RoomNumber)
                  else
                    SET @WareText = @WareText + ' to ref. '+Convert(varchar,@ReferenceNumber)+ '/ ' +Convert(varchar,@GuestNumber)

                  if @TransferedFromLastName<>''
                    SET @WareText = @WareText +  ', '   + @TransferedFromLastName
                end
                else if ((@FolioNumber>0) AND (@ReferenceNumber=0 ))
                begin
                  SET @WareText = @WareText + ' from folio '+Convert(varchar,@FolioNumber)
                  if @TransferedFromLastName<>''
                    SET @WareText = @WareText +  ', '  + @TransferedFromLastName
                end

                if @TransferToFolioNumber<=0  SET @TransferToFolioNumber = @FolioNumber

                IF @SeparateEconomyByStaffDep = 1
                BEGIN
                  -- Get department from DerpartmentService from the ware, and use the autoDay user
                  SET @tmpDepartment = @FK_DepartmentNumber 

                  SELECT TOP 1 @FK_DepartmentNumber = wdXTab.FK_Department
                  FROM WareDepartmentsXTab wdXTab WITH (NOLOCK) 
                  INNER JOIN Departments d WITH (NOLOCK) ON d.PK_Department = wdXTab.FK_Department AND wdXTab.Type = 2 --DepartmentService
                  WHERE WareNumber = @WareNumber
                  AND ((@CentralBookingType NOT IN (3,7)) OR (d.HotelNumber IN (SELECT HotelNumber FROM Customer WITH (NOLOCK) WHERE CustomerTypeNumber = 7 AND CustomerNumber = @HotelCustomerNumber)))
                END 

                --SET @GlobalTransactionNumber=@GlobalTransactionNumber+1
                EXEC GetNextNumber 'GLOBALTRANSACTIONIDENTITY', 1, @GlobalTransactionNumber OUTPUT

                INSERT INTO Transactions (ProductNumber, PackageNumber, GlobalTransactionNumber, OriginalGlobalTransactionNumber, RealDateTimeForTransaction, PAXadult, PAXChild1, PAXChild2, DateStamp, UserIDNumber, FolioNumber, Pieces, PriceOverwrite, CurrencyNumber, ShowOnBillFlag, Debit, MovedDeleted, WareNumber, TextOverwrite, Payment, AccountNumber, VATValue, /*DepartmentOverwrite*/ FK_DepartmentNumber, Note, OriginalDate,ExchangeRateOverwrite,ProductWareLinkNumber,GuestNumber, AutoReceivedPayment, HotelCustomerNumber, ChargedWithCard, FK_ArrangementLineNumber)
                VALUES(0, 0, @GlobalTransactionNumber, @GlobalTransactionNumber, @RealDateTimeForTransaction, @PaxAdult, @PaxChild1, @PaxChild2, @RealDateTimeForTransaction, @UserIDNumber, @TransferToFolioNumber,ABS(@Pieces), @WarePrice, @MyCountryNumber, 1, 0, 0,@WareNumber, @WareText, @Payment, @BalanceAccountNumber, 0, /*@Department*/ @FK_DepartmentNumber, @Note, @PostForDatetime,@ExchangeRate,@ProductWareLinkNumber, @GuestNumber, 0, @TransferToHotelCustomerNumber, @ChargedWithCard, @AArrangementLineNumber)
                IF @UseCashDesk = 1
                BEGIN
                  SELECT @LastTransactionNumber = @@Identity
                  EXEC TransactionsRelationInsert @LastTransactionNumber, @ACashDesk, @UserIDNumber
                END

                INSERT INTO Transactions (ProductNumber, PackageNumber, GlobalTransactionNumber, OriginalGlobalTransactionNumber, RealDateTimeForTransaction, PAXadult, PAXChild1, PAXChild2, DateStamp, UserIDNumber, FolioNumber, Pieces, PriceOverwrite, CurrencyNumber, ShowOnBillFlag, Debit, MovedDeleted, WareNumber, TextOverwrite, Payment, AccountNumber, VATValue, /*DepartmentOverwrite*/ FK_DepartmentNumber, Note, OriginalDate,ExchangeRateOverwrite,ProductWareLinkNumber,GuestNumber, AutoReceivedPayment, HotelCustomerNumber, ChargedWithCard, FK_ArrangementLineNumber)
                VALUES(0, 0, @GlobalTransactionNumber, @GlobalTransactionNumber, @RealDateTimeForTransaction, @PaxAdult, @PaxChild1, @PaxChild2, @RealDateTimeForTransaction, @UserIDNumber, @TransferToFolioNumber,ABS(@Pieces), @WarePrice, @MyCountryNumber, 0, 1, 0,@WareNumber, @WareText, @Payment, @PaymentBalanceAccountNumber, 0, /*@Department*/ @FK_DepartmentNumber, @Note, @PostForDatetime,@ExchangeRate,@ProductWareLinkNumber, @GuestNumber, 0, @TransferToHotelCustomerNumber, @ChargedWithCard, @AArrangementLineNumber)
                IF @UseCashDesk = 1
                BEGIN
                  SELECT @LastTransactionNumber = @@Identity
                  EXEC TransactionsRelationInsert @LastTransactionNumber, @ACashDesk, @UserIDNumber
                END

                IF @SeparateEconomyByStaffDep = 1
                  SET @FK_DepartmentNumber = @tmpDepartment 
              END
            END
          end
          else
          begin
            if @Payment = 11 -- wanted deposit
              SET @Debit = 0
            else
              SET @Debit = 1

            IF @Correction = 1
              SELECT TOP 1 @ExchangeRate = ExchangeRateOverwrite, @MyCountryNumber = CurrencyNumber FROM Transactions WITH (NOLOCK) WHERE GlobalTransactionNumber = @GlobalTransactionNumber

            INSERT INTO Transactions (ProductNumber, PackageNumber, GlobalTransactionNumber, OriginalGlobalTransactionNumber, RealDateTimeForTransaction, PAXadult, PAXChild1, PAXChild2, DateStamp, UserIDNumber, FolioNumber, Pieces, PriceOverwrite, CurrencyNumber, ShowOnBillFlag, Debit, MovedDeleted, WareNumber, TextOverwrite, Payment, AccountNumber, VATValue, /*DepartmentOverwrite*/ FK_DepartmentNumber, Note, OriginalDate,ExchangeRateOverwrite,ProductWareLinkNumber, DepositFollowupNumber,GuestNumber, AutoReceivedPayment, HotelCustomerNumber, ChargedWithCard, FK_ArrangementLineNumber)
            VALUES(0, 0, @GlobalTransactionNumber, @GlobalTransactionNumber, @RealDateTimeForTransaction, @PaxAdult, @PaxChild1, @PaxChild2,  @RealDateTimeForTransaction, @UserIDNumber,@FolioNumber,@Pieces, @WarePrice, @MyCountryNumber, 0, @Debit, 0,@WareNumber,@WareText, @Payment, @BalanceAccountNumber,0, /*@Department*/ @FK_DepartmentNumber, @Note, @PostForDatetime,@ExchangeRate,@ProductWareLinkNumber, @DepositFollowupNumber, @GuestNumber, @AutoReceivedPayment, @HotelCustomerNumber, @ChargedWithCard, @AArrangementLineNumber)
            IF @UseCashDesk = 1
            BEGIN
              SELECT @LastTransactionNumber = @@Identity
              EXEC TransactionsRelationInsert @LastTransactionNumber, @ACashDesk, @UserIDNumber
            END

            if @Payment = 11 -- wanted deposit
            begin
              SET @Debit = 1
              SET @ShowOnBillFlag = 0
            end 
            else
            begin
              SET @Debit = 0
              if @Payment = 10
                SET @ShowOnBillFlag = 0
              else
                SET @ShowOnBillFlag = 1
            end

            INSERT INTO Transactions (ProductNumber, PackageNumber, GlobalTransactionNumber, OriginalGlobalTransactionNumber, RealDateTimeForTransaction, PAXadult, PAXChild1, PAXChild2, DateStamp, UserIDNumber, FolioNumber, Pieces, PriceOverwrite, CurrencyNumber, ShowOnBillFlag, Debit, MovedDeleted, WareNumber, TextOverwrite, Payment, AccountNumber, VATValue, /*DepartmentOverwrite*/ FK_DepartmentNumber, Note, OriginalDate,ExchangeRateOverwrite,ProductWareLinkNumber, DepositFollowupNumber,GuestNumber, AutoReceivedPayment, HotelCustomerNumber, ChargedWithCard, FK_ArrangementLineNumber)
            VALUES(0, 0, @GlobalTransactionNumber, @GlobalTransactionNumber, @RealDateTimeForTransaction, @PaxAdult, @PaxChild1, @PaxChild2, @RealDateTimeForTransaction, @UserIDNumber, @FolioNumber,@Pieces, @WarePrice, @MyCountryNumber, @ShowOnBillFlag, @Debit, 0,@WareNumber, @WareText, @Payment, @PaymentBalanceAccountNumber, 0, /*@Department*/ @FK_DepartmentNumber, @Note, @PostForDatetime, @ExchangeRate,@ProductWareLinkNumber, @DepositFollowupNumber, @GuestNumber, @AutoReceivedPayment, @HotelCustomerNumber, @ChargedWithCard, @AArrangementLineNumber)
            IF @UseCashDesk = 1
            BEGIN
              SELECT @LastTransactionNumber = @@Identity
              EXEC TransactionsRelationInsert @LastTransactionNumber, @ACashDesk, @UserIDNumber
            END
          end
        end
      end

      if @InterfaceNumber > 0 AND (@Correction=0)
      begin
        Declare @UserTypeNumber TinyInt
        Select @UserTypeNumber = UserTypeNumber from Personel WITH (Nolock) where UserIDNumber = @UserIDNumber

        if @UserTypeNumber = 3 -- Autoday
        begin
          Declare @DiscountWareNumber Int
          Declare @Discount money
          Declare @DiscountWareText varchar(50)
          Declare @InterfaceType varchar(30)
          Declare @DiscountRate money

          SELECT @DiscountWareNumber = Ware.WareNumber, @DiscountWareText = Ware.WareName 
          FROM Ware WITH (NOLOCK) 
          INNER JOIN WareGroups WITH (NOLOCK) ON WareGroups.WareGroupNumber = Ware.WareGroupNumber
            AND WareGroups.Payment = 5 and ISNULL(WareGroups.MarkAsDeleted, '0') = '0'
          WHERE Ware.Type = 19 -- Discount

          if @DiscountWareNumber >0
          begin
            Select @InterfaceType = Type from Interfaces WITH (Nolock) where IntNo = @InterfaceNumber

            if  Upper(@InterfaceType) = 'TELEPHONE' AND @PhoneAndPayTvDiscount in (1,3) -- Phone + all
            begin 
              exec GetDiscountRate @ReferenceNumber, @GuestNumber, @AddressType, 4, @DiscountRate output
              SET @Discount = @WarePrice * (@DiscountRate/100)
            end  
            else
            if  Upper(@InterfaceType) = 'PAY TV'  AND @PhoneAndPayTvDiscount in (2,3) -- TV + all   
            begin
              exec GetDiscountRate @ReferenceNumber, @GuestNumber, @AddressType, 5, @DiscountRate output
              SET @Discount = @WarePrice * (@DiscountRate/100)
            end
            else 
              SET @Discount = 0

            if @Discount>0 
            begin
              SET @WareText = RTRIM(LTRIM(Str(@DiscountRate, 5, 2) + ' % ' +' ' + @DiscountWareText+ ' ' + @WareText))

              exec Postering 0, 0, 1, 0, 0, 0, @UserIDNumber, @FolioNumber, 0, 0, 0, 0, @WareText, @Pieces, @Discount, @MyCountryNumber, 0, 0, 0, 0, /*@Department*/ @FK_DepartmentNumber, @DiscountWareNumber, 0, 0 , 0, 0, @Note, @DummyTransNrShowOnBillOnAdd OUTPUT, @ChargedWithCard = @ChargedWithCard, @ACashDesk=@ACashDesk
            end
          end
        end
      end
    end
    else if (@MovedFolioNumber <> 0) AND (@MovedTransactionNumber>0)
    begin
      -- Flytning
      Declare @CurserCreated bit
      Declare @TransactionNumber int
      Declare @TempGlobalTransactionNumber int
      Declare @TempPayment tinyint
      Declare @MovedDeletedOnSourceTran Bit
      Declare @WareGroupPayment tinyint
      Declare @TempPieces int
      DECLARE @CurrentGlobalTransactionNumber INT
      DECLARE @GTN INT
      DECLARE @GTN1 INT
      DECLARE @GTN2 INT
      SET @GTN2 = 0

      if isnull(@ProductWareLinkNumber,0)=0 
        SET @ProductWareLinkNumber = 0 

      if (@WareIsHallRoom = 1) AND (@ProductWareLinkNumber>0)-- modposter pakke
      begin
        SET @CurserCreated = 1
        IF @Pieces = 0 -- Move 
          SET @MovedDeletedOnSourceTran = 1
        ELSE -- reduction
          SET @MovedDeletedOnSourceTran = 0

        Declare PackageContentsCur Cursor Read_only Fast_forward For
        Select
          ShowOnBillFlag, ProductWareLinkNumber, TransactionNumber, Transactions.ProductNumber, PackageNumber, GlobalTransactionNumber,
          PAXadult, PAXChild1, PAXChild2, Payment, Pieces, PriceOverwrite, CurrencyNumber, Transactions.AccountNumber,
          Debit, VATValue, FK_DepartmentNumber, Note, ExchangeRateOverwrite, GuestNumber, WareNumber, TextOverwrite,
          OriginalDate, DepositFollowupNumber, AccountType, DateStamp, AutoReceivedPayment
        from Transactions WITH (NOLOCK)
          INNER JOIN ACCOUNTS WITH (NOLOCK) on Accounts.AccountNumber = Transactions.AccountNumber
          where FolioNumber=@FolioNumber AND ProductWareLinkNumber = @ProductWareLinkNumber AND ((MovedDeleted is null) or (MovedDeleted=0))
      end
      else -- flytning af ikke-logitrans
      begin
        SET @CurserCreated = 1

        Declare PackageContentsCur Cursor READ_ONLY Fast_forward For
        Select
          ShowOnBillFlag, 0, Transactions.TransactionNumber, Transactions.ProductNumber, PackageNumber, GlobalTransactionNumber,
          PAXadult, PAXChild1, PAXChild2, Transactions.Payment, Pieces, PriceOverwrite, CurrencyNumber, Transactions.AccountNumber,
          Debit, VATValue, FK_DepartmentNumber, Transactions.Note, ExchangeRateOverwrite, GuestNumber, Transactions.WareNumber,
          TextOverwrite, OriginalDate, DepositFollowupNumber, AccountType, KitchenStatementNumber, TransactionKitchenStatementXTab.Note,
          DateStamp, AutoReceivedPayment, WareGroups.Payment
        from Transactions WITH (NOLOCK)
          INNER JOIN ACCOUNTS WITH (NOLOCK) on Accounts.AccountNumber = Transactions.AccountNumber
          LEFT OUTER JOIN TransactionKitchenStatementXTab WITH (nolock) on Transactions.TransactionNumber = TransactionKitchenStatementXTab.TransactionNumber
          INNER JOIN Ware WITH (Nolock) on Ware.WareNumber = Transactions.WareNumber
          INNER JOIN WareGroups WITH (Nolock) on WareGroups.WareGroupNumber = Ware.WareGroupNumber
        where FolioNumber=@FolioNumber AND GlobalTransactionNumber=@GlobalTransactionNumber AND ((MovedDeleted is null) or (MovedDeleted=0))

        IF @ShowPrint = 1
        BEGIN 
          print @FolioNumber
          print @GlobalTransactionNumber
        END
      end

      if @CurserCreated=1
      begin
        if (@WareIsHallRoom = 1) AND (@ProductWareLinkNumber>0)-- modposter pakke
        begin
          Open PackageContentsCur

          Fetch Next From PackageContentsCur Into @ShowOnBillFlag, @ProductWareLinkNumber,@TransactionNumber, @ProductNumber, @PackageNumber, @TempGlobalTransactionNumber, @PAXadult, @PAXChild1, @PAXChild2, @TempPayment,
            @TempPieces, @WarePrice, @MyCountryNumber,@AccountNumber, @Debit, @VatValueWare, @FK_DepartmentNumber, @Note, @ExchangeRate,
            @GuestNumber, @WareNumber, @WareText,@OriginalDate, @TempDepositFollowupNumber, @AccountType, @TransactionDateStamp, @AutoReceivedPayment

          EXEC GetNextNumber 'PRODUCTWARELINKIDENTITY', 1, @NewProductWareLinkNumberWhenMoveDelete OUTPUT
          EXEC GetNextNumber 'PRODUCTWARELINKIDENTITY', 1, @NewProductWareLinkNumberWhenMoveDelete1 OUTPUT

          SELECT @OriginalPrice = PriceOverwrite, @OriginalPieces = Pieces FROM Transactions WITH (NOLOCK) 
          WHERE FolioNumber = @FolioNumber 
          AND GlobalTransactionNumber=@GlobalTransactionNumber 
          AND ISNULL(MovedDeleted, 0) = 0
          AND ShowOnBillFlag = 1

          IF @OriginalPrice <> @Price
            SET @ReductionPercent = CAST(@Price AS FLOAT)/CAST(@OriginalPrice AS FLOAT)
          ELSE IF @OriginalPieces <> @Pieces
            SET @ReductionPercent = CAST(@Pieces AS FLOAT)/CAST(@OriginalPieces AS FLOAT)
          ELSE
            SET @ReductionPercent = 0
            
          SET @CurrentGlobalTransactionNumber = @TempGlobalTransactionNumber
          EXEC GetNextNumber 'GLOBALTRANSACTIONIDENTITY', 1, @GTN OUTPUT
          EXEC GetNextNumber 'GLOBALTRANSACTIONIDENTITY', 1, @GTN1 OUTPUT
        end
        else
        begin
          Open PackageContentsCur

          Fetch Next From PackageContentsCur Into @ShowOnBillFlag, @ProductWareLinkNumber,@TransactionNumber, @ProductNumber, @PackageNumber, @TempGlobalTransactionNumber, @PAXadult, @PAXChild1, @PAXChild2, @TempPayment,
            @TempPieces, @WarePrice, @MyCountryNumber,@AccountNumber, @Debit, @VatValueWare, @FK_DepartmentNumber, @Note, @ExchangeRate,
            @GuestNumber, @WareNumber, @WareText,@OriginalDate, @TempDepositFollowupNumber, @AccountType, @KitchenStatementNumber, @KitchenTransNote, @TransactionDateStamp, @AutoReceivedPayment, @WareGroupPayment
            
          SET @cntTransfer = 0
          SELECT @cntTransfer = COUNT(*)
          FROM TransactionTransactionXtab WITH (NOLOCK)
          WHERE (FK_TransactionNumber1 = @MovedTransactionNumber OR FK_TransactionNumber2 = @MovedTransactionNumber)
          AND RelationType = 2

          SET @NewProductWareLinkNumberWhenMoveDelete = NULL
          IF @IsMenuWare = 1 OR ISNULL(@cntTransfer, 0) > 0
          BEGIN 
            SELECT @OriginalPrice = PriceOverwrite FROM Transactions WITH (NOLOCK) 
            WHERE FolioNumber=@FolioNumber 
            AND GlobalTransactionNumber=@GlobalTransactionNumber 
            AND ISNULL(MovedDeleted, 0) =0
            AND ShowOnBillFlag = 1

            IF @OriginalPrice <> @Price
              SET @ReductionPercent = CAST(@Price AS FLOAT)*@Pieces/CAST(@OriginalPrice AS FLOAT)
            ELSE IF @TempPieces <> @Pieces
              SET @ReductionPercent = CAST(@Pieces AS FLOAT)/CAST(@TempPieces AS FLOAT)
            ELSE
              SET @ReductionPercent = 0
          END
        end
        
        WHILE @@Fetch_Status = 0
        BEGIN
          SET @TranTranOrgId = 0

          IF @ShowPrint = 1
            PRINT 'Package loop begin before fix @MyCountryNumber='+CONVERT (VARCHAR, @MyCountryNumber);    
        
          IF ISNULL(@MyCountryNumber, 0) <= 0
          BEGIN
            IF ISNULL(@CountryNumber, 0) <= 0
            BEGIN
              SELECT @MyCountryNumber = CONVERT(INT,KeyValue) FROM HotelSetup WITH (NOLOCK) WHERE SearchKey='CountryCode'
              IF @@ROWCOUNT = 0
                SELECT TOP 1 @MyCountryNumber = CountryNumber FROM Countries WITH (NOLOCK)
            END
            ELSE
              SET @MyCountryNumber = @CountryNumber
          END

          IF @ShowPrint = 1
            PRINT 'Package loop begin after fix @MyCountryNumber='+ CONVERT (VARCHAR, @MyCountryNumber);    

          if (@OriginalDate is null)
            SET @OriginalDate =  @RealDateTimeForTransaction

          if @Debit=1
            SET @INVDebit =  0
          else
            SET @INVDebit =  1

          IF (@TempPayment=12) AND (@ReservationStatus IN (5,6) AND (@AccountType = 9)) -- AccountType = 9 = Deposit wanted
            SET @AccountNumber = @BalanceAccountNumber

          if NOT((@WareIsHallRoom = 1) AND (@ProductWareLinkNumber>0))
          begin
            if ((@WareGroupPayment in (0,2,3,7,8)) AND ((@Pieces<>0) AND (@Price<>0))) -- "normal ware" + rooms/halls
            begin
              SET @MovedDeletedOnSourceTran = 0
              SET @Pieces = ABS(@Pieces)
              SET @TempPieces = @Pieces

              IF @IsMenuWare = 1 OR ISNULL(@cntTransfer, 0) > 0
                SET @WarePrice = ABS(@WarePrice*@ReductionPercent)
              ELSE
              BEGIN
                if  @AccountType = 5 -- debtor
                  SET @WarePrice = Round(ABS(@Price* @Pieces),2)
                else if  @AccountType = 3  -- ware
                  SET @WarePrice = ABS((@Price* @Pieces) * ((1/convert(float,((@VatValueWare/100)+1)))))
                else if  @AccountType = 2  -- VAT
                  SET @WarePrice = ABS(@Price* @Pieces*(1-(1/convert(float,((@VatValueWare/100)+1)))))
              END    
            end
            else
            begin
              SET @MovedDeletedOnSourceTran = 1
            end
          end
          ELSE
          BEGIN
            IF ISNULL(@ReductionPercent, 0) <> 0
            BEGIN
              SET @WarePrice = ABS(@WarePrice*@ReductionPercent)
              SET @TempPieces = @Pieces*-1
            END              
          END

          if @MovedDeletedOnSourceTran=1
          begin
            IF @ShowPrint = 1
              print '@MovedDeletedOnSourceTran=1'

            UPDATE Transactions SET  MovedDeleted = 1, MovedFolioNr = @MovedFolioNumber
            WHERE TransactionNumber=@TransactionNumber
          end

          IF (CONVERT(CHAR(8), @TransactionDateStamp,112) > @CurrentDateStr)
          BEGIN
            SET @TransactionDateStr = CONVERT(CHAR(8), @TransactionDateStamp, 112)
            EXEC SystemDateTime @TransactionDateStr, @NewChargeDayWhenMoveDelete OUTPUT
          END
          ELSE
            SET @NewChargeDayWhenMoveDelete = @RealDateTimeForTransaction

          if @MovedDeletedOnSourceTran = 1
          begin
            INSERT INTO Transactions (ProductNumber, PackageNumber, GlobalTransactionNumber, OriginalGlobalTransactionNumber, RealDateTimeForTransaction, PAXadult, PAXChild1, PAXChild2, DateStamp, UserIDNumber, FolioNumber, Pieces, PriceOverwrite, CurrencyNumber, ShowOnBillFlag, Debit, MovedDeleted, MovedFolioNr, WareNumber, TextOverwrite, Payment, AccountNumber, VATValue, FK_DepartmentNumber, Note, OriginalDate, ExchangeRateOverwrite, GuestNumber, ProductWareLinkNumber, DepositFollowupNumber, AutoReceivedPayment, HotelCustomerNumber, ChargedWithCard, FK_ArrangementLineNumber)
            VALUES(@ProductNumber, @PackageNumber, @TempGlobalTransactionNumber, @GlobalTransactionNumber, @RealDateTimeForTransaction, @PaxAdult, @PaxChild1, @PaxChild2, @NewChargeDayWhenMoveDelete, @UserIDNumber, @FolioNumber, -@TempPieces, @WarePrice, @MyCountryNumber, @ShowOnBillFlag, @INVDebit, @MovedDeletedOnSourceTran, @MovedFolioNumber, @WareNumber, @WareText, @TempPayment, @AccountNumber, @VatValueWare, @FK_DepartmentNumber, @Note, @OriginalDate, @ExchangeRate, @GuestNumber, @NewProductWareLinkNumberWhenMoveDelete, @TempDepositFollowupNumber, @AutoReceivedPayment, @HotelCustomerNumber, @ChargedWithCard, @AArrangementLineNumber)
            SELECT @LastTransactionNumber = @@Identity
            IF @UseCashDesk = 1
              EXEC TransactionsRelationInsert @LastTransactionNumber, @ACashDesk, @UserIDNumber
            IF @ShowOnBillFlag = 1
              EXEC PostTranTranXtab @TransactionNumber, @LastTransactionNumber

            INSERT INTO Transactions (ProductNumber, PackageNumber, GlobalTransactionNumber, OriginalGlobalTransactionNumber, RealDateTimeForTransaction, PAXadult, PAXChild1, PAXChild2, DateStamp, UserIDNumber, FolioNumber, Pieces, PriceOverwrite, CurrencyNumber, ShowOnBillFlag, Debit, MovedDeleted, MovedFolioNr, WareNumber, TextOverwrite, Payment, AccountNumber, VATValue, FK_DepartmentNumber, Note, OriginalDate, ExchangeRateOverwrite, GuestNumber, ProductWareLinkNumber, DepositFollowupNumber, AutoReceivedPayment, HotelCustomerNumber, ChargedWithCard, FK_ArrangementLineNumber)
            VALUES(@ProductNumber, @PackageNumber, @TempGlobalTransactionNumber, @GlobalTransactionNumber, @RealDateTimeForTransaction, @PaxAdult, @PaxChild1, @PaxChild2, @NewChargeDayWhenMoveDelete, @UserIDNumber, @MovedFolioNumber, @TempPieces, @WarePrice, @MyCountryNumber, @ShowOnBillFlag, @Debit, 0,@FolioNumber, @WareNumber, @WareText, @TempPayment, @AccountNumber, @VatValueWare, @FK_DepartmentNumber, @Note, @OriginalDate, @ExchangeRate, @GuestNumber, (@NewProductWareLinkNumberWhenMoveDelete1), @TempDepositFollowupNumber, @AutoReceivedPayment, @HotelCustomerNumber, @ChargedWithCard, @AArrangementLineNumber)
            SELECT @LastTransactionNumber = @@Identity
            IF @UseCashDesk = 1
            BEGIN
              SELECT @LastTransactionNumber = @LastTransactionNumber
              EXEC TransactionsRelationInsert @LastTransactionNumber, @ACashDesk, @UserIDNumber
            END
            IF @ShowOnBillFlag = 1
            BEGIN
              UPDATE TransactionOnlinePaymentXtab
              SET FK_TransactionNumber = @LastTransactionNumber
              WHERE FK_TransactionNumber = @MovedTransactionNumber
            END
          end
          else
          begin 
            -- Reduction           
            IF (@WareIsHallRoom = 1) AND (@ProductWareLinkNumber>0)-- modposter pakke
            BEGIN
              IF @CurrentGlobalTransactionNumber <> @TempGlobalTransactionNumber
              BEGIN
                EXEC GetNextNumber 'GLOBALTRANSACTIONIDENTITY', 1, @GTN OUTPUT
                EXEC GetNextNumber 'GLOBALTRANSACTIONIDENTITY', 1, @GTN1 OUTPUT
              END
            END
            ELSE
              SET @GTN = @FirstGlobaltransactionNumber
            
            IF @ShowOnBillFlag = 1 AND @GTN2 = 0
              SET @GTN2 = @GTN

            IF @MovedFolioNumber > 0
            BEGIN
              INSERT INTO Transactions (ProductNumber, PackageNumber, GlobalTransactionNumber, OriginalGlobalTransactionNumber, RealDateTimeForTransaction, PAXadult, PAXChild1, PAXChild2, DateStamp, UserIDNumber, FolioNumber, Pieces, PriceOverwrite, CurrencyNumber, ShowOnBillFlag, Debit, MovedDeleted, MovedFolioNr, WareNumber, TextOverwrite, Payment, AccountNumber, VATValue, FK_DepartmentNumber, Note, OriginalDate, ExchangeRateOverwrite, GuestNumber, ProductWareLinkNumber, DepositFollowupNumber, AutoReceivedPayment, HotelCustomerNumber, ChargedWithCard, FK_ArrangementLineNumber)
              VALUES(@ProductNumber, @PackageNumber, @GTN, @TempGlobalTransactionNumber, @RealDateTimeForTransaction, @PaxAdult, @PaxChild1, @PaxChild2, @NewChargeDayWhenMoveDelete, @UserIDNumber, @FolioNumber, -@TempPieces, @WarePrice, @MyCountryNumber, @ShowOnBillFlag, @INVDebit, @MovedDeletedOnSourceTran, @MovedFolioNumber, @WareNumber, @WareText, @TempPayment, @AccountNumber, @VatValueWare, @FK_DepartmentNumber, @Note, @OriginalDate, @ExchangeRate, @GuestNumber, @NewProductWareLinkNumberWhenMoveDelete, @TempDepositFollowupNumber, @AutoReceivedPayment, @HotelCustomerNumber, @ChargedWithCard, @AArrangementLineNumber)
            END
            ELSE
            BEGIN
              INSERT INTO Transactions (ProductNumber, PackageNumber, GlobalTransactionNumber, OriginalGlobalTransactionNumber, RealDateTimeForTransaction, PAXadult, PAXChild1, PAXChild2, DateStamp, UserIDNumber, FolioNumber, Pieces, PriceOverwrite, CurrencyNumber, ShowOnBillFlag, Debit, MovedDeleted, MovedFolioNr, WareNumber, TextOverwrite, Payment, AccountNumber, VATValue, FK_DepartmentNumber, Note, OriginalDate, ExchangeRateOverwrite, GuestNumber, ProductWareLinkNumber, DepositFollowupNumber, AutoReceivedPayment, HotelCustomerNumber, ChargedWithCard, FK_ArrangementLineNumber)
              VALUES(@ProductNumber, @PackageNumber, @GTN, @TempGlobalTransactionNumber, @RealDateTimeForTransaction, @PaxAdult, @PaxChild1, @PaxChild2, @NewChargeDayWhenMoveDelete, @UserIDNumber, @FolioNumber, -@TempPieces, @WarePrice, @MyCountryNumber, @ShowOnBillFlag, @INVDebit, @MovedDeletedOnSourceTran, NULL, @WareNumber, @WareText, @TempPayment, @AccountNumber, @VatValueWare, @FK_DepartmentNumber, @Note, @OriginalDate, @ExchangeRate, @GuestNumber, @NewProductWareLinkNumberWhenMoveDelete, @TempDepositFollowupNumber, @AutoReceivedPayment, @HotelCustomerNumber, @ChargedWithCard, @AArrangementLineNumber)
            END

            SELECT @LastTransactionNumber = @@Identity

            IF @ShowOnBillFlag = 1 AND @ATranRelationType > 0
              SET @TranTranOrgId = @LastTransactionNumber
              
            IF @UseCashDesk = 1
              EXEC TransactionsRelationInsert @LastTransactionNumber, @ACashDesk, @UserIDNumber
            
            IF @MovedFolioNumber > 0
            BEGIN
              IF @CurrentGlobalTransactionNumber <> @TempGlobalTransactionNumber OR ISNULL(@GTN1, 0) = 0
                EXEC GetNextNumber 'GLOBALTRANSACTIONIDENTITY', 1, @GTN1 OUTPUT
              INSERT INTO Transactions (ProductNumber, PackageNumber, GlobalTransactionNumber, OriginalGlobalTransactionNumber, RealDateTimeForTransaction, PAXadult, PAXChild1, PAXChild2, DateStamp, UserIDNumber, FolioNumber, Pieces, PriceOverwrite, CurrencyNumber, ShowOnBillFlag, Debit, MovedDeleted, MovedFolioNr, WareNumber, TextOverwrite, Payment, AccountNumber, VATValue, FK_DepartmentNumber, Note, OriginalDate, ExchangeRateOverwrite, GuestNumber, ProductWareLinkNumber, DepositFollowupNumber, AutoReceivedPayment, HotelCustomerNumber, ChargedWithCard, FK_ArrangementLineNumber)
              VALUES(@ProductNumber,  @PackageNumber, @GTN1, @TempGlobalTransactionNumber, @RealDateTimeForTransaction, @PaxAdult, @PaxChild1, @PaxChild2, @NewChargeDayWhenMoveDelete, @UserIDNumber, @MovedFolioNumber, @TempPieces, @WarePrice, @MyCountryNumber, @ShowOnBillFlag, @Debit, 0,@FolioNumber, @WareNumber, @WareText, @TempPayment, @AccountNumber, @VatValueWare, @FK_DepartmentNumber, @Note, @OriginalDate, @ExchangeRate, @GuestNumber,(@NewProductWareLinkNumberWhenMoveDelete1), @TempDepositFollowupNumber, @AutoReceivedPayment, @HotelCustomerNumber, @ChargedWithCard, @AArrangementLineNumber)
              SELECT @LastTransactionNumber = @@Identity
              IF @UseCashDesk = 1
                EXEC TransactionsRelationInsert @LastTransactionNumber, @ACashDesk, @UserIDNumber
              IF @ShowOnBillFlag = 1
              BEGIN
                IF @MovedTransactionNumber > 0 AND @LastTransactionNumber > 0 AND @ATranRelationType > 0
                  INSERT INTO TransactionTransactionXtab (FK_TransactionNumber1, FK_TransactionNumber2, RelationType) VALUES (@MovedTransactionNumber, @LastTransactionNumber, @ATranRelationType)
                IF @TranTranOrgId <= 0
                  EXEC PostTranTranXtab @TransactionNumber, @LastTransactionNumber
              END
            END  

            SET @CurrentGlobalTransactionNumber = @TempGlobalTransactionNumber

            IF @FirstGlobaltransactionNumberOnlyOnce = -1
              EXEC GetNextNumber 'GLOBALTRANSACTIONIDENTITY', 1, @FirstGlobaltransactionNumberOnlyOnce OUTPUT
            SET @GlobaltransactionNumber = @FirstGlobaltransactionNumberOnlyOnce+1
          end
          IF @ShowPrint = 1
		  begin
            PRINT '---Kitchen ---'
            PRINT '@MovedFolioNumber= ' + CONVERT(VARCHAR, @MovedFolioNumber)
            PRINT '@ShowOnBillFlag= ' + CONVERT(VARCHAR, @ShowOnBillFlag)
            PRINT '@KitchenStatementNumber= ' + CONVERT(VARCHAR, ISNULL(@KitchenStatementNumber,0))
		  end

          IF @MovedFolioNumber > 0 AND (@ShowOnBillFlag=1) and (@KitchenStatementNumber>0)
          begin
            IF @UseCashDesk = 1
              SET @DummyTransNrShowOnBillOnAdd = @LastTransactionNumber
            ELSE
              SET @DummyTransNrShowOnBillOnAdd = (Select @@IDENTITY)

            UPDATE TransactionKitchenStatementXTab SET Changed = 0 WHERE TransactionNumber=@TransactionNumber

            DECLARE @KitchenTableNumber INT
            SET @KitchenTableNumber = 0
            IF ISNULL((SELECT TOP 1 KeyValue FROM HotelSetup WITH (NOLOCK) WHERE SearchKey LIKE 'KitchenPrintMovedTransAction'),1) = 1
            BEGIN 
			  DECLARE @FkFolio INT
              SELECT @FkFolio = FkFolio FROM Folios WITH (NOLOCK) WHERE (FolioNumber = @FolioNumber)
              IF ISNULL(@FkFolio, 0) = 0  
                IF ISNULL(@TableBooking,0)=0
                  SELECT TOP 1 @KitchenTableNumber= TableNumber FROM FolioRestResTableChairsXTab WITH (NOLOCK) WHERE (FolioNumber = @MovedFolioNumber)
                ELSE
                  SELECT TOP 1 @KitchenTableNumber = ConferenceRooms.Number 
				  FROM FolioRestResTableChairsXTab X WITH (NOLOCK) 
				    JOIN ConferenceRooms WITH (NOLOCK) ON X.TableNumber = ConferenceRooms.ConferenceRoomNumber
                  WHERE (X.FolioNumber = @MovedFolioNumber)
            END

            DECLARE @KitchenNote VARCHAR(255) 
            SELECT @KitchenNote=Note FROM TransactionKitchenStatementXTab WITH (NOLOCK) WHERE TransactionNumber=@TransactionNumber

            IF ISNULL(@KitchenTableNumber,0) > 0 AND CONVERT(DATE, @RealDateTimeForTransaction) = Convert(DATE,@CurrentDateStr)
              INSERT INTO TransactionKitchenStatementXTab (TransactionNumber, KitchenStatementNumber, Changed, Note) VALUES (@DummyTransNrShowOnBillOnAdd,  @KitchenStatementNumber, 1, @KitchenNote)
            ELSE
              INSERT INTO TransactionKitchenStatementXTab (TransactionNumber, KitchenStatementNumber, Changed, Note) VALUES (@DummyTransNrShowOnBillOnAdd,  @KitchenStatementNumber, 0, @KitchenNote)
          end
          IF @ShowPrint = 1
		  begin
            PRINT '@TableBooking= ' + CONVERT(VARCHAR, ISNULL(@TableBooking, 0))
            PRINT '@KitchenTableNumber= ' + CONVERT(VARCHAR, ISNULL(@KitchenTableNumber, 0))
            PRINT '@RealDateTimeForTransaction= ' + CONVERT(VARCHAR, Convert(int, @RealDateTimeForTransaction))
            PRINT '@CurrentDateStr= ' + CONVERT(VARCHAR, Convert(int,Convert(DateTime,@CurrentDateStr)))
            PRINT '---Kitchen End---'
		  end

          if (@WareIsHallRoom = 1) AND (@ProductWareLinkNumber>0)-- modposter pakke
          begin
            Fetch Next From PackageContentsCur Into @ShowOnBillFlag,@ProductWareLinkNumber,@TransactionNumber, @ProductNumber, @PackageNumber,@TempGlobalTransactionNumber, @PAXadult, @PAXChild1, @PAXChild2, @TempPayment,
              @TempPieces, @WarePrice, @MyCountryNumber,@AccountNumber, @Debit, @VatValueWare, /*@Department*/ @FK_DepartmentNumber, @Note, @ExchangeRate,
              @GuestNumber, @WareNumber, @WareText,@OriginalDate,@TempDepositFollowupNumber, @AccountType, @TransactionDateStamp, @AutoReceivedPayment
          end
          else
          begin
            Fetch Next From PackageContentsCur Into @ShowOnBillFlag, @ProductWareLinkNumber,@TransactionNumber, @ProductNumber, @PackageNumber,@TempGlobalTransactionNumber, @PAXadult, @PAXChild1, @PAXChild2, @TempPayment,
              @TempPieces, @WarePrice, @MyCountryNumber,@AccountNumber, @Debit, @VatValueWare, /*@Department*/ @FK_DepartmentNumber, @Note, @ExchangeRate,
              @GuestNumber, @WareNumber, @WareText,@OriginalDate, @TempDepositFollowupNumber, @AccountType, @KitchenStatementNumber, @KitchenTransNote, @TransactionDateStamp, @AutoReceivedPayment, @WareGroupPayment
          end
        end

        Close PackageContentsCur
        Deallocate PackageContentsCur
      end
    end
  end

  if @Correction=1
  begin
    if @MovedTransactionNumber > 0 OR (@Payment = 11 AND @DepositFollowupNumber>0) OR (@PostDiscount=1)
    begin
      if @Payment=5
      begin
        UPDATE Transactions SET MovedDeleted  = 1
        WHERE GlobalTransactionNumber = (SELECT TOP 1 GlobalTransactionNumber FROM Transactions WITH (NOLOCK) WHERE Transactionnumber=@MovedTransactionNumber) AND FolioNumber = @FolioNumber
      end
      else
      begin
        if ((@WareIsHallRoom = 1) AND (@ProductWareLinkNumber>0)) OR (@Payment = 11 AND @DepositFollowupNumber>0) OR (@PostDiscount=1) OR (@AddonWare = 1) -- modposter pakke
        begin
          IF @WareIsHallRoom = 1 AND @ProductWareLinkNumber>0
          BEGIN
            Declare PackageContentsCur1 Cursor STATIC Read_Only For
              Select Transactions.ProductNumber, PackageNumber, GlobalTransactionNumber, PAXadult, PAXChild1, PAXChild2, Payment,
                Pieces, PriceOverwrite, CurrencyNumber, AccountNumber, Debit, VATValue, FK_DepartmentNumber, Note, ExchangeRateOverwrite,
                GuestNumber, WareNumber, TextOverwrite, DepositFollowupNumber, FolioNumber, ProductWareLinkNumber, ShowOnBillFlag,
                DateStamp, UserIDNumber, AutoReceivedPayment
              from Transactions WITH (NOLOCK)
              where FolioNumber=@FolioNumber 
              AND ProductWareLinkNumber = @ProductWareLinkNumber
              AND MovedDeleted=0  
          END
          ELSE IF @Payment = 11 AND @DepositFollowupNumber>0
          BEGIN
            Declare PackageContentsCur1 Cursor STATIC Read_Only For
              Select Transactions.ProductNumber, PackageNumber, GlobalTransactionNumber, PAXadult, PAXChild1, PAXChild2, Payment,
                Pieces, PriceOverwrite, CurrencyNumber, AccountNumber, Debit, VATValue, FK_DepartmentNumber, Note, ExchangeRateOverwrite,
                GuestNumber, WareNumber, TextOverwrite, DepositFollowupNumber, FolioNumber, ProductWareLinkNumber, ShowOnBillFlag,
                DateStamp, UserIDNumber, AutoReceivedPayment
              from Transactions WITH (NOLOCK)
              where DepositFollowupNumber=@DepositFollowupNumber 
              AND Payment = 11
              AND MovedDeleted=0  
          END
          ELSE IF @Payment = 0 AND (@PostDiscount=1 OR @AddonWare = 1) 
          BEGIN
            Declare PackageContentsCur1 Cursor STATIC Read_Only For
              Select Transactions.ProductNumber, PackageNumber, GlobalTransactionNumber, PAXadult, PAXChild1, PAXChild2, Payment,
                Pieces, PriceOverwrite, CurrencyNumber, AccountNumber, Debit, VATValue, FK_DepartmentNumber, Note, ExchangeRateOverwrite,
                GuestNumber, WareNumber, TextOverwrite, DepositFollowupNumber, FolioNumber, ProductWareLinkNumber, ShowOnBillFlag,
                DateStamp, UserIDNumber, AutoReceivedPayment
              from Transactions WITH (NOLOCK)
              where Globaltransactionnumber=@Globaltransactionnumber
              AND MovedDeleted=0  
          END 

          Open PackageContentsCur1

          Fetch Next From PackageContentsCur1 Into @ProductNumber, @PackageNumber,@GlobalTransactionNumber, @PAXadult, @PAXChild1, @PAXChild2, @Payment,
             @Pieces, @WarePrice, @MyCountryNumber,@AccountNumber, @Debit, @VatValueWare, @FK_DepartmentNumber, @Note, @ExchangeRate,
             @GuestNumber, @WareNumber, @WareText, @TempDepositFollowupNumber,@FolioNumber, @ProductWareLinkNumber, @ShowOnBillFlag, @TransactionDateStamp, @UserIDNumberInTrans, @AutoReceivedPayment

          if (@UserIDNumber is Null) OR (@UserIDNumber=0)
            SET @UserIDNumber = @UserIDNumberInTrans 

          IF ISNULL(@ProductWareLinkNumber, 0) > 0
            EXEC GetNextNumber 'PRODUCTWARELINKIDENTITY', 1, @NewProductWareLinkNumberWhenMoveDelete OUTPUT
          ELSE
            SET @NewProductWareLinkNumberWhenMoveDelete = NULL
          
          While (@@Fetch_Status=0)
          Begin
            IF @ShowPrint = 1
              PRINT 'Package loop begin before fix @MyCountryNumber='+ CONVERT (VARCHAR, @MyCountryNumber);    

            IF ISNULL(@MyCountryNumber, 0) <= 0
            BEGIN
              IF ISNULL(@CountryNumber, 0) <= 0
              BEGIN
                SELECT @MyCountryNumber = CONVERT(INT,KeyValue) FROM HotelSetup WITH (NOLOCK) WHERE SearchKey='CountryCode'
                IF @@ROWCOUNT = 0
                  SELECT TOP 1 @MyCountryNumber = CountryNumber FROM Countries WITH (NOLOCK)
              END
              ELSE
                SET @MyCountryNumber = @CountryNumber
            END

            IF @ShowPrint = 1
              PRINT 'Package loop begin after fix @MyCountryNumber='+ CONVERT (VARCHAR, @MyCountryNumber);    
          
            if @Debit=1
              SET @INVDebit =  0
            else
              SET @INVDebit =  1

            IF (CONVERT(CHAR(8), @TransactionDateStamp,112) > @CurrentDateStr)
            BEGIN
              SET @TransactionDateStr = CONVERT(CHAR(8), @TransactionDateStamp, 112)
              EXEC SystemDateTime @TransactionDateStr, @NewChargeDayWhenMoveDelete OUTPUT
            END
            ELSE
              SET @NewChargeDayWhenMoveDelete = @PostForDatetime

            INSERT INTO Transactions (ProductNumber, PackageNumber, GlobalTransactionNumber, OriginalGlobalTransactionNumber, RealDateTimeForTransaction, PAXadult, PAXChild1, PAXChild2, DateStamp, UserIDNumber, FolioNumber, Pieces, PriceOverwrite, CurrencyNumber, ShowOnBillFlag, Debit, MovedDeleted, WareNumber, TextOverwrite, Payment, AccountNumber, VATValue, FK_DepartmentNumber, Note, OriginalDate, ExchangeRateOverwrite, GuestNumber, ProductWareLinkNumber, DepositFollowupNumber, AutoReceivedPayment, HotelCustomerNumber, ChargedWithCard, FK_ArrangementLineNumber)
            VALUES(@ProductNumber, @PackageNumber, @GlobalTransactionNumber, @GlobalTransactionNumber, @RealDateTimeForTransaction, @PaxAdult, @PaxChild1, @PaxChild2, @NewChargeDayWhenMoveDelete, @UserIDNumber,@FolioNumber,-@Pieces,@WarePrice, @MyCountryNumber, @ShowOnBillFlag, @INVDebit, 1, @WareNumber, @WareText, @Payment, @AccountNumber, @VatValueWare, @FK_DepartmentNumber, @Note, @NewChargeDayWhenMoveDelete, @ExchangeRate, @GuestNumber, @NewProductWareLinkNumberWhenMoveDelete, @TempDepositFollowupNumber, @AutoReceivedPayment, @HotelCustomerNumber, @ChargedWithCard, @AArrangementLineNumber)
            IF @UseCashDesk = 1
            BEGIN
              SELECT @LastTransactionNumber = @@Identity
              EXEC TransactionsRelationInsert @LastTransactionNumber, @ACashDesk, @UserIDNumber
            END

            Fetch Next From PackageContentsCur1 Into @ProductNumber, @PackageNumber,@GlobalTransactionNumber, @PAXadult, @PAXChild1, @PAXChild2, @Payment,
              @Pieces, @WarePrice, @MyCountryNumber,@AccountNumber, @Debit, @VatValueWare, @FK_DepartmentNumber, @Note, @ExchangeRate,
              @GuestNumber, @WareNumber, @WareText,@TempDepositFollowupNumber,@FolioNumber,@ProductWareLinkNumber,@ShowOnBillFlag, @TransactionDateStamp, @UserIDNumberInTrans, @AutoReceivedPayment
          end

          if ((@WareIsHallRoom = 1) AND (@ProductWareLinkNumber>0))
          begin
            Update Transactions SET MovedDeleted  = 1
            WHERE TransactionNumber IN ( 
              SELECT TransactionNumber FROM Transactions T WITH (NOLOCK) 
              WHERE ProductWareLinkNumber = @ProductWareLinkNumber AND MovedDeleted=0
              EXCEPT
              SELECT TransactionNumber FROM Transactions T WITH (NOLOCK) 
              INNER JOIN dbo.InvoiceTransactionXTab ITX WITH (NOLOCK) ON T.TransactionNumber = ITX.FkTransaction
              INNER JOIN dbo.Invoice I WITH (NOLOCK) ON ITX.FkInvoice = I.PkInvoice AND I.CancelDate IS NULL AND ReceiptType <> 0 
              WHERE ProductWareLinkNumber = @ProductWareLinkNumber AND MovedDeleted=0
            )
          end
          else if (@PostDiscount=1) OR (@AddonWare = 1)
          begin
            Update Transactions SET MovedDeleted  = 1
            WHERE TransactionNumber IN ( 
              SELECT TransactionNumber FROM Transactions T WITH (NOLOCK) 
              WHERE GlobalTransactionNumber = @GlobalTransactionNumber AND MovedDeleted=0
              EXCEPT
              SELECT TransactionNumber FROM Transactions T WITH (NOLOCK) 
              INNER JOIN dbo.InvoiceTransactionXTab ITX WITH (NOLOCK) ON T.TransactionNumber = ITX.FkTransaction
              INNER JOIN dbo.Invoice I WITH (NOLOCK) ON ITX.FkInvoice = I.PkInvoice AND I.CancelDate IS NULL AND ReceiptType <> 0
              WHERE GlobalTransactionNumber = @GlobalTransactionNumber AND MovedDeleted=0
            )
          end
          else
          begin
            Update Transactions SET MovedDeleted  = 1
            WHERE TransactionNumber IN ( 
              SELECT TransactionNumber FROM Transactions T WITH (NOLOCK) 
              WHERE DepositFollowupNumber=@DepositFollowupNumber AND MovedDeleted=0
              EXCEPT
              SELECT TransactionNumber FROM Transactions T WITH (NOLOCK) 
              INNER JOIN dbo.InvoiceTransactionXTab ITX WITH (NOLOCK) ON T.TransactionNumber = ITX.FkTransaction
              INNER JOIN dbo.Invoice I WITH (NOLOCK) ON ITX.FkInvoice = I.PkInvoice AND I.CancelDate IS NULL AND ReceiptType <> 0
              WHERE DepositFollowupNumber=@DepositFollowupNumber AND MovedDeleted=0
            )
          end

          Close PackageContentsCur1
          Deallocate PackageContentsCur1
        end
        else
        begin
          UPDATE Transactions SET MovedDeleted  = 1
          WHERE GlobalTransactionNumber = (
            SELECT TOP 1 GlobalTransactionNumber FROM Transactions WITH (NOLOCK) 
            WHERE TransactionNumber IN ( 
              SELECT TransactionNumber FROM Transactions T WITH (NOLOCK) 
              WHERE Transactionnumber=@MovedTransactionNumber
              EXCEPT
              SELECT TransactionNumber FROM Transactions T WITH (NOLOCK) 
              INNER JOIN dbo.InvoiceTransactionXTab ITX WITH (NOLOCK) ON T.TransactionNumber = ITX.FkTransaction
              INNER JOIN dbo.Invoice I WITH (NOLOCK) ON ITX.FkInvoice = I.PkInvoice AND I.CancelDate IS NULL AND ReceiptType <> 0
              WHERE Transactionnumber=@MovedTransactionNumber
            )
          )
        end
      end
    end
    else
    begin
      if @DepositFollowupNumber = 0
      begin
        if @Payment=5 -- sletning af transfer
        begin
          Update Transactions SET MovedDeleted  = 1
          WHERE FolioNumber = @FolioNumber AND GlobalTransactionNumber IN ( 
            SELECT GlobalTransactionNumber FROM Transactions T WITH (NOLOCK) 
            WHERE GlobalTransactionNumber = @GlobalTransactionNumber AND FolioNumber = @FolioNumber 
            EXCEPT
            SELECT GlobalTransactionNumber FROM Transactions T WITH (NOLOCK) 
            INNER JOIN dbo.InvoiceTransactionXTab ITX WITH (NOLOCK) ON T.TransactionNumber = ITX.FkTransaction
            INNER JOIN dbo.Invoice I WITH (NOLOCK) ON ITX.FkInvoice = I.PkInvoice AND I.CancelDate IS NULL AND ReceiptType <> 0
            WHERE GlobalTransactionNumber = @GlobalTransactionNumber AND FolioNumber = @FolioNumber 
          )
        end
        else -- sletning af ware + andre betalinger
        begin
          Update Transactions SET MovedDeleted  = 1
          WHERE GlobalTransactionNumber IN ( 
            SELECT GlobalTransactionNumber FROM Transactions T WITH (NOLOCK) 
            WHERE GlobalTransactionNumber = @GlobalTransactionNumber 
            EXCEPT
            SELECT GlobalTransactionNumber FROM Transactions T WITH (NOLOCK) 
            INNER JOIN dbo.InvoiceTransactionXTab ITX WITH (NOLOCK) ON T.TransactionNumber = ITX.FkTransaction
            INNER JOIN dbo.Invoice I WITH (NOLOCK) ON ITX.FkInvoice = I.PkInvoice AND I.CancelDate IS NULL AND ReceiptType <> 0
            WHERE GlobalTransactionNumber = @GlobalTransactionNumber 
          )
        end
      end 
      else
      begin
        Update Transactions SET MovedDeleted  = 1
        WHERE TransactionNumber IN ( 
          SELECT TransactionNumber FROM Transactions T WITH (NOLOCK) 
          WHERE DepositFollowupNumber=@DepositFollowupNumber AND Payment=11
          EXCEPT
          SELECT TransactionNumber FROM Transactions T WITH (NOLOCK) 
          INNER JOIN dbo.InvoiceTransactionXTab ITX WITH (NOLOCK) ON T.TransactionNumber = ITX.FkTransaction
          INNER JOIN dbo.Invoice I WITH (NOLOCK) ON ITX.FkInvoice = I.PkInvoice AND I.CancelDate IS NULL AND ReceiptType <> 0
          WHERE DepositFollowupNumber=@DepositFollowupNumber AND Payment=11
        )
      end 
    end
  end
end
END -- end of "IF ISNULL(@@ERROR,0) = 0"

if (@Correction=0)
BEGIN
  SELECT @TransNrShowOnBillOnAdd = MAX(TransactionNumber), @AOriginalGlobalTransactionNumber = MAX(OriginalGlobalTransactionNumber) 
  FROM Transactions WITH (NOLOCK) 
  WHERE GlobalTransactionNumber = @GlobalTransactionNumber 
  AND ShowOnBillFlag = 1 
  AND MovedDeleted=0

  IF ISNULL(@TransNrShowOnBillOnAdd, 0) = 0 AND @FirstGlobaltransactionNumber > 0
  BEGIN
    SELECT @TransNrShowOnBillOnAdd = MAX(TransactionNumber), @AOriginalGlobalTransactionNumber = MAX(OriginalGlobalTransactionNumber) 
    FROM Transactions WITH (NOLOCK) 
    WHERE GlobalTransactionNumber = @FirstGlobaltransactionNumber 
    AND ShowOnBillFlag = 1 
    AND MovedDeleted=0
  END

  IF ISNULL(@TransNrShowOnBillOnAdd, 0) = 0 AND @GTN2 > 0
  BEGIN
    SELECT @TransNrShowOnBillOnAdd = MAX(TransactionNumber), @AOriginalGlobalTransactionNumber = MAX(OriginalGlobalTransactionNumber) 
    FROM Transactions WITH (NOLOCK) 
    WHERE GlobalTransactionNumber = @GTN2 
    AND ShowOnBillFlag = 1 
    AND MovedDeleted=0
  END

  IF ISNULL(@TransNrShowOnBillOnAdd, 0) > 0 AND ISNULL(@AMainTransactionNumber, 0) > 0 -- Sideorder
    INSERT INTO TransactionTransactionXTab (FK_TransactionNumber1, FK_TransactionNumber2, RelationType) VALUES (@AMainTransactionNumber, @TransNrShowOnBillOnAdd, 1)
END
ELSE IF ISNULL(@tmpGlobalTransactionNumber, 0) > 0 AND @Correction=1 AND @MovedTransactionNumber > 0
BEGIN
  DECLARE db_cur_movdel CURSOR LOCAL READ_ONLY FOR
    SELECT COUNT(*), MovedDeleted FROM Transactions WITH (NOLOCK) 
    WHERE GlobaltransactionNumber = @tmpGlobalTransactionNumber
    AND FolioNumber = @tmpFolioNumber
    AND ISNULL(MovedFolioNr, 0) = 0
    GROUP BY MovedDeleted
  OPEN db_cur_movdel

  IF @@CURSOR_ROWS > 1
    RAISERROR('Error in storedprocedure <<postering>>: Delete transaction failed.',15,1)

  CLOSE db_cur_movdel
  DEALLOCATE db_cur_movdel
  SELECT TOP 1 @TransNrShowOnBillOnAdd = MAX(TransactionNumber) 
  FROM Transactions WITH (NOLOCK) 
  WHERE GlobalTransactionNumber = @tmpGlobalTransactionNumber 
  AND ShowOnBillFlag = 1 
  AND MovedDeleted=1
END

IF ISNULL(@Correction, 0) = 0
  EXEC PostGiftCertificate @WareNumber, @AOriginalGlobalTransactionNumber, @Note, @Payment, @HotelCustomerNumber, @Price, @ADoNotGetNewGiftTokenId -- @Note is actually GiftTokenNumber

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

DECLARE @SqlStr VARCHAR(25)
SET @SqlStr = 'SET LOCK_TIMEOUT '+ CONVERT(VARCHAR, @LockTimeOut)
EXEC (@SqlStr)