CREATE PROCEDURE dbo.PostPackage @FolioNumber int, @ReferenceNumber int, @GuestNumber int, @SplitBillNumber int, @LodgingAccount int, @MoveToPackageDeb bit, @MoveFromPackageDeb bit, @PriceOverWritten bit, 
  @RoomTypeNumber int, @UserIDNumber Integer, @PacketNumber int, @ProductNumber int, @NumberOfRooms int, @Date Datetime, @Adult int, @Children1 int, @Children2 int, @PriceoverwriteValue Money, 
  @FK_TurnoverDepartmentNumber INT, @DiscountValue Float = 0, @PacketTurnOver Money OUTPUT, @VatOfPacketTurnOver Money OUTPUT, @PacketTurnOverDiscount MONEY OUTPUT, @ProductWareLinkNumber int=-1, @CurrencyNumber int = 1, @HotelCustomerNumber INT, 
  @ChargeOnSystemDate bit = 0, @PostAllLines BIT = 0, @TableReservationLineNumber INT = 0, @ACashDesk INT = -1, @AConferenceRoomLineNumber INT = 0, @ANumberOfGuests INT = 1, @ARealGuestNumber INT = 0, 
  @APostCityTax BIT = 0, @ALogiVATValue FLOAT = 0, @ARoomTotalPrice MONEY = 0 AS
SET NOCOUNT ON

/*
  Changes:
 KJ 20250409: Menu ware allowed even if splitdoes not add up if UseForResidualAmount is set
 KJ 20241125: Ext: Added post discount on packageline
 KJ 20241008: Bug: Fix for "Wrong hotel number used when charge packet department enabled".
 KJ 20240214: Added timeZone.
 KJ 20230713: Ext: AllowZero price setting from Ware added, so package is chargen even if price is zero.
 KJ 20211101: Bug: Fix for "Priceoverwrite is negative when post package with menu ware not in percent". Case #CR210092
 KJ 20210927: Bug: Fix for "Wrong folionumber when post hall line with no product and different guest type in splitbill setup". Case #CR208676
 KJ 20191125: Bug: Fix for "Packge not posted when bonus card on reservation due to trigger on Folios table". Case #CR174296
 KJ 20190704: Bug: Fix for "Amount wrong if running "% Package split after fixed amount", package has lines with type 2, 6 and 9, and Number of rooms > 1". Case# CR166957
 KJ 20181008: Support for Mixed resources
 KJ 20171102: Ext: City tax
 KJ 20170705: Bug: Fix for "Posting on wrong folionumber when post room". Case #CR129347
 KJ 20170704: Bug: Fix for "Posting on wrong folionumber when post room". Case #CR129347
 KJ 20170630: Bug: Fix for "Posting on wrong folionumber when running charge package department enabled and post per hall name". Case #CR129119
 KJ 20161201: Bug: Fix for "Wrong amount posted if menuware". Case #CR116869
 KJ 20160829: Ext: Post halls per person. Req 3115
 KJ 20150612: Bug: Fix for "Package posted multiple times when charge packet department enabled and multiple hall lines on same day and use tolerance time is disabled". Case #CR088649
 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
 KJ 20140624: Ext: Menu ware split in whole amount. Req #1561
 KJ 20140611: Ext: CashDesk per hotel. Case #CR073269
 KJ 20140213: Ext: Use packet charge department when post product.  
 KJ 20120320: Bug: Fix for "Must declare the scalar variable "@FK_LogiTurnoverDepartment".". Case #CR053139 
 KJ 20130219: Bug: Fix for "Wrong department in post product when post on res folio". Case #CR052439 
 KJ 20121009: Bug: Fix for "Wrong Pieces and debit when PostProduct and using a negative number of rooms for debtype 2,6,9 and dayproduct" Case "CR050973
 KJ 20121009: Bug: Fix for "Wrong Pieces and debit when PostProduct and using a negative number of rooms for debtype 2,6,9" Case "CR047388
 KJ 20120611: Bug: Fix for "Wrong Pieces and debit when PostProduct and using a negative number of rooms for debtype 2,6,9" Case "CR044072
 KJ 20120214: Bug: Fix for "Wrong pieces and debit when PostProduct and using a negative number of rooms". Case #CR039846
 KJ 20111025: Bug: Another try to fix ""Price/Pieces wrong when number of rooms is less than 0" Case# CR034936
 KJ 20110307: Ext: Menuware in package. Req# 818
 KJ 20110211: Bug: Fix for "Price/Pieces wrong when number of rooms is less than 0" Case# CR018253 + CR019552 and other
 KJ 20101208: Bug: Fix for "Price/Pieces wrong when number of rooms is less than 0" Case# CR018253
 KJ 20101208: Bug: Fix for "Not all package lines posted when running packageChargeDepartment and Domino". Case# CR018294
 KJ 20100610: Bug/Ext: Using department from packageline when running charge department enabled.
 KJ 20091208: Ext: Added CashDesk
 KJ 20081222: Ext: Added OriginalGlobalTransactionNumber
 KJ 20081112: Bug: Fix for Forfait not posted correct for pieces < 0
 KJ 20081121: Ext: Added extended Forfait - post only if selected on packet line
 KJ 20081024: Bug: Fix for "Package charged with wrong amount for PostProduct and more that one pieces"
 KJ 20080714: Ext: Added forfait posting
 KJ 20080612: Bug: Fix for "Wrong pieces for debtype 2,6,9 and a negativ number of rooms"
 KJ 20080414: Bug: Fix for "Post package by department sometimes post on wrong department"
 KJ 20080313: Bug: Fix for Package charged on wrong dates when precharge.
 KJ 20080204: Ext: Optimized SQL for ChargePacketDepartment
 KJ 20071220: Bug: Package for table reservations posted on wrong folio.
 KJ 20071017: Bug: HotelNumber not used when arr.line is shown on reservation.
 KJ 20071017: Bug: Fix for "Department type is 1 for "DepartmentServiceOverwrite"
 KJ 20070817: Bug: Fix for "Wrong departmentnumber on transactions"
 KJ 20070817: Bug: Fix for "Using Department service overwrite when chargebypakage isn't activated."
 KJ 20070530: Bug: Fix for "Invalid object name 'Departmetns'."
 KJ 20070427: Bug: Fix for "Not all arrangementlines/packagelines charged"
 KJ 20070423: Bug: Fix for: "Arrangementlines does not match...."
 KJ 20070423: Bug: Fix for "Invalid object name 'Departmetns'."
 KJ 20070410: Department rewrite
 KJ 20070410: Fix for "Turnoverdepartment wrong if running Domino"
 KJ 20070328: BUG: Fix for Package lines with same name not posted. Distinct is used.
 KJ 20070130: Fix for Packagelines for dayproducts not charged if shown on reservation
 KJ 20070115: Fix for Packagelines on reservation not posted to PackageDeb account on departureDate
 KJ 20070112: Fix for Packagelines on reservation not posted to PackageDeb account on departureDate
 KJ 20061211: Added '@PostAllLines BIT = 0' as default input param. Used to ensure that all package lines gets posted when "charge d-product" (call from PostProduct sp.
 KJ 20061211: Added 'CONVERT(VARCHAR(8),'  to Arrangementdate.
 KJ 20061205: Fix for Sometimes packagelines posted twice.
 KJ 20061027: Packetlines that are not shown on reservation not charged when package charge by department
 KJ 20061006: Fix for "Charge d-product not working - ReferenceNumber is null"
 KJ 20060826: Added PacketItem_NewRoomTypeXtab (Some package items are related to specific roomtypes)
 KJ 20060620: Getting chargedepartment from arragementlines if any. else using @TurnoverDepartment
 KJ 20060601: Only charge packet items with department related to the correct hotel in Domino
 KJ 20050901: Removed AccountDaily
 JP 20050526: changed to use GetNextNumber SP
 Rettet d. 21/02-2005 af KS : DiscountAsNettoPrice
 Rettet d. 21/02-2005 af KS : Allways calc discount
 Rettet d. 27/01-2005 af KS : No * with pieces when priceoverwrited
 Rettet d. 20/09-2004 af KS : Some round stuff
 Rettet d. 20/09-2004 af KS : Changed pricefields from float to money
 Rettet d. 15/09-2004 af KS : Some optimization
 Rettet d. 14/05-2004 af KS : Imp. HotelCustomerNumber for Multihotel
 Rettet d. 16/03-2004 : Bug package-split after reduction of fix-amount
 Rettet d. 03/02-2004 : changed department to char(1)
 Rettet d. 27/01-2004 : Imp minus in price in package
 Rettet d. 06/01-2004 : Imp package-split after reduction of fix-amount
 Rettet d. 11/12-2003 : Added discount for packagedeb
 Rettet d. 25/11-2003 : Fixed bug with 1,4,7 debtype
 Rettet d. 29/09-2003 : Removed Round when set @WarePriceWithOutVAT
 Rettet d. 04/09-2003 : remove excl/vat from transtext
 Rettet d. 06/05-2003 : Added parameter @ChargeOnSystemDate = 0
 Rettet d. 30/04-2003 : Fixed Problem with %-package
 Rettet d. 30/01-2003 : new getnextglobaltransactionnumber
 Rettet d. 16/01-2003 : Added read_only and Fast_forward to cursor dec.
 Rettet d. 04/12-2002 : imp CurrencyNumber
 Rettet d. 02/9-2002 : Use convert(float) in VATOFPrice
 Rettet d. 26/8-2002 : Sæt date til idag hvis mindre end denne
*/

Declare @Print bit
SET @Print = 0

if @Print=1
begin
  PRINT 'POSTPackage START'
  Print '@ReferenceNumber'
  Print @ReferenceNumber
  Print '@NumberOfRooms'
  Print @NumberOfRooms
  Print '@PacketNumber'
  Print @PacketNumber
  print '@DiscountValue'
  print @DiscountValue
  PRINT '@Date'
  PRINT @Date
  PRINT '@MoveToPackageDeb'
  PRINT @MoveToPackageDeb 
  PRINT '@MoveFromPackageDeb'
  PRINT @MoveFromPackageDeb
  PRINT '@PostAllLines'
  PRINT @PostAllLines
  PRINT '@ProductNumber'
  PRINT @ProductNumber
end

DECLARE @CityTaxEnabled BIT
DECLARE @CityTaxWareNumber INT
DECLARE @CityTaxWareText VARCHAR(50)
DECLARE @CityTaxInPercent BIT
DECLARE @CityTaxPrice MONEY
DECLARE @CityTaxResultAccountNumber INT
DECLARE @CityTaxBalanceAccountNumber INT
DECLARE @CityTaxVATAccountNumber INT
DECLARE @CityTaxWarePrice MONEY
DECLARE @CityTaxVATValueNumber TINYINT
DECLARE @CityTaxVATValueWare FLOAT
DECLARE @CityTaxVatOfPrice MONEY
DECLARE @CityTaxPacketTurnOver MONEY
DECLARE @DiscountAmount MONEY

If (@PacketNumber>0)
Begin
  SELECT @CityTaxEnabled = CONVERT(BIT, KeyValue) FROM HotelSetup WITH (NOLOCK) WHERE SearchKey = 'CityTaxEnable'
  SET @CityTaxEnabled = ISNULL(@CityTaxEnabled, 0) 

  IF @CityTaxEnabled = 1 --AND @PostCityTax = 1
  BEGIN
    -- Get City tax ware info
    SELECT @CityTaxWareText = WareName, @CityTaxWareNumber = WareNumber, @CityTaxInPercent = PriceInPercent, 
      @CityTaxResultAccountNumber = ResultAccountNumber, @CityTaxBalanceAccountNumber = BalanceAccountNumber,
      @CityTaxWarePrice = Price, @CityTaxVATValueNumber = Accounts.VATValueNumber, @CityTaxVATAccountNumber = Accounts.VatAccountNumber
    FROM Ware WITH (NOLOCK)
    INNER JOIN ACCOUNTS WITH (NOLOCK) ON  Ware.ResultAccountNumber = Accounts.AccountNumber
    WHERE Type = 28 -- City Tax

    EXEC GetVatvalueFromVATValueNumber @CityTaxVATValueNumber, @CityTaxVATValueWare OUTPUT 
  END

  IF ISNULL(@ARealGuestNumber, -1) <= 0
    SET @ARealGuestNumber = @GuestNumber

  Declare @AddressType smallint
  Declare @PackageDebAccount int
  Declare @StartDateStr Char(8)
  Declare @EndDateStr Char(8)
  Declare @DateStr Char(8)

  Declare @WareNumber Int
  Declare @WarePrice Money
  Declare @DebitType SmallInt

  Declare @ResultAccountNumber Integer
  Declare @BalanceAccountNumber Integer
  Declare @StockAccountNumber Integer
  Declare @VATAccountNumber Integer
  Declare @VATValueNumber Integer

  Declare @VatValueWare Float

  Declare @VatByPacketValue Money
  Declare @VatOfPacket Money

  Declare @RoomPriceAdult Money
  Declare @RoomPriceChildren1 Money
  Declare @RoomPriceChildren2 Money

  Declare @PostDatetime DateTime
  Declare @RealDateTimeForTransaction DateTime

  Declare @Pieces SmallInt

  Declare @WareText VARChar(50)

  Declare @VatValueWareText VARChar(6)

  Declare @I SmallInt

  Declare @LogiWareNumber int
  Declare @DayProduct bit

  Declare @VATProduct bit

  Declare @CurrentDate char(8)
  Declare @IsFixedPriceProduct bit

  Declare @PackagesplitAfterReduction bit

  Declare @FixAmountSum Money
  Declare @ReductionAfterSplitSum Money

  Declare @PercentDebType INT

  Declare @SubWareFromReduction int

  Declare @DiscountAsNettoPrice bit

  Declare @ReservationDiscount bit

  Declare @ArrivalAddon Money
  Declare @StayAddon Money 
  Declare @DepartureAddon Money

  DECLARE @HotelNumber INT

  DECLARE @FK_ChargeDepartmentNumber INT
  DECLARE @ChargePacketDepartmentEnabled BIT
  DECLARE @tmpDep INT

  DECLARE @SortNumber INT

  DECLARE @PostForfait BIT

  DECLARE @UseCashDesk BIT
  DECLARE @LastTransactionNumber INT
  
  DECLARE @IsMenuWare BIT

  DECLARE @MenuWareName VARCHAR(50)
  DECLARE @MenuProcentage MONEY
  DECLARE @MenuResultAccountNumber INT
  DECLARE @MenuBalanceAccountNumber INT
  DECLARE @MenuPaymentBalanceAccountNumber INT
  DECLARE @MenuWareSortNumber INT
  DECLARE @MenuSingleWareNumber INT
  DECLARE @MenuWarePrice FLOAT
  DECLARE @MenuVatValueNumber INT
  DECLARE @MenuVATAccountNumber INT
  DECLARE @MenuVatValueWare FLOAT
  DECLARE @PostProductUsePacketDepartment BIT
  DECLARE @DefaultPacketDepartment INT
  DECLARE @InPercent BIT
  DECLARE @WareCityTax BIT
  DECLARE @AllowZeroPrice BIT

  DECLARE @ArrangementLineNumber INT
  
  DECLARE @PostHallPerGuest BIT

  DECLARE @TotalPrice MONEY
  DECLARE @IsResidual BIT
  DECLARE @ResidualNeeded BIT
  DECLARE @LocalPieces INT

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

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

  Select @PackagesplitAfterReduction =  Convert(bit, KeyValue) From Hotelsetup WITH (Nolock) where Searchkey ='PackagesplitAfterReduction'
  if isnull(@PackagesplitAfterReduction,0) =0 SET @PackagesplitAfterReduction = 0

  Select @ChargePacketDepartmentEnabled = Convert(bit, KeyValue) From Hotelsetup WITH (Nolock) where Searchkey ='ChargePacketDepartmentEnabled'
  if isnull(@ChargePacketDepartmentEnabled,0) = 0 SET @ChargePacketDepartmentEnabled = 0

  Select @SubWareFromReduction = Convert(Int, KeyValue) From Hotelsetup WITH (Nolock) where Searchkey ='SubWareFromReduction'
  if isnull(@SubWareFromReduction,0) =0 SET @SubWareFromReduction = 0

  Select @DiscountAsNettoPrice =  ISNULL(KeyValue,0) From Hotelsetup WITH (Nolock) where Searchkey ='DiscountAsNettoPrice'

  SELECT @PostProductUsePacketDepartment = ISNULL(KeyValue, 0) FROM Hotelsetup WITH (NOLOCK) WHERE Searchkey ='PostProductUsePacketDepartment'
  SET @PostProductUsePacketDepartment = ISNULL(@PostProductUsePacketDepartment, 0)

  DECLARE @CentralBookingType SMALLINT
  Select @CentralBookingType = Convert(Integer,isnull(KeyValue,0)) from HotelSetup WITH (Nolock) where searchkey like '%CentralBookingType%'

  DECLARE @ChargeDiscountAsProduct BIT
  SELECT @ChargeDiscountAsProduct = CONVERT(BIT, KeyValue) FROM HotelSetup WITH (NOLOCK) WHERE SearchKey = 'ChargeDiscountAsProduct'
  SET @ChargeDiscountAsProduct = ISNULL(@ChargeDiscountAsProduct, 1)

  DECLARE @DiscountOnPackageLine BIT
  SELECT @DiscountOnPackageLine = KeyValue FROM HotelSetup WITH (NOLOCK) WHERE SearchKey = 'DiscountOnPackageLine'
  SET @DiscountOnPackageLine = ISNULL(@DiscountOnPackageLine, 0)

  DECLARE @DummyOrgGT INT
  DECLARE @DummyTransNrShowOnBillOnAdd INT
  DECLARE @TempStr VARCHAR(60)
  DECLARE @DiscountWareNumber INT
  DECLARE @DiscountWareText VARCHAR(50)
  DECLARE @NumOfDecimals INT

  SET @DiscountWareNumber = 0	
  SELECT @DiscountwareText = Ware.WareName, @DiscountWareNumber = Ware.WareNumber, @NumOfDecimals = ISNULL(NumberOfDecimals, 2)
  FROM Ware WITH (NOLOCK)
  INNER JOIN WareGroups WITH (NOLOCK) ON WareGroups.WareGroupNumber = Ware.WareGroupNumber
    AND WareGroups.Payment = 5  
  WHERE Ware.Type = 19
  AND Ware.MarkAsDeleted IS NULL

  SET @PacketTurnOver = 0
  SET @VatOfPacketTurnOver = 0
  SET @CityTaxPacketTurnOver = 0
  SET @PacketTurnOverDiscount = 0

  SET @ReductionAfterSplitSum = 0

  SET @PostAllLines = ISNULL(@PostAllLines, 0)

  if @ProductNumber>0
  begin
    Select @IsFixedPriceProduct = FixedPrice, @VATProduct = ExcludeVAT, @DayProduct = DayProduct 
    From Products WITH (nolock) 
    WHERE ProductNumber=@ProductNumber

    if (@VATProduct is null) 
      SET @VATProduct=1
    else
    begin
      if @VATProduct=0 
        SET @VATProduct=1
      else
        SET @VATProduct = 0
    end
  end
  else
  begin
    SET @VATProduct = 1
    SET @IsFixedPriceProduct = 0
  end

  if (@ProductWareLinkNumber<=-1) SET @ProductWareLinkNumber = NULL

  SET @HotelNumber = -1
  IF @HotelCustomerNumber > -1
    SELECT @HotelNumber = HotelNumber FROM Customer WITH (NOLOCK) WHERE CustomerNumber = @HotelCustomerNumber

  IF @PostProductUsePacketDepartment = 1
  BEGIN
    IF ISNULL(@ReferenceNumber, 0) > 0
    BEGIN
      SELECT @DefaultPacketDepartment = PK_Department FROM Departments d WITH (NOLOCK)
      INNER JOIN ReservationMain r WITH (NOLOCK) ON d.HotelNumber = r.HotelNumber AND AutoCharge = 1 AND ReferenceNumber = @ReferenceNumber
      AND ISNULL(MarkAsDeleted, 0)= 0
      ORDER BY d.SortNumber
    
      IF ISNULL(@DefaultPacketDepartment, 0) = 0
        SELECT TOP 1 @DefaultPacketDepartment = PK_Department FROM Departments WITH (NOLOCK) WHERE ISNULL(MarkASDeleted,0) = 0 ORDER BY SortNumber
    END
  END 

  IF (@ChargePacketDepartmentEnabled = 1) AND (ISNULL(@ReferenceNumber, 0) > 0) AND (@PostAllLines = 0)
  BEGIN
    Declare #WareCur Cursor  static Read_Only forward_only For
    SELECT DISTINCT
      ArrangementLines.ArrangementLineNumber,
      PacketItem_New.SortNumber,
      Departments.PK_Department,
      Ware.ResultAccountNumber,
      Ware.BalanceAccountNumber,
      Ware.StockAccountNumber,
      Ware.WareNumber,
      PacketItem_New.PriceOverWrite,
      PacketItem_New.TextOverwrite,
      PacketItem_New.DebType,
      CASE WHEN Ware.WareNumber = @CityTaxWareNumber THEN 99999 ELSE CASE WHEN PacketItem_New.DebType IN (2,6,9) THEN 1 ELSE 0 END END AS PercentDebType,
      Accounts.VatValueNumber,
      Accounts.VATAccountNumber,
      isnull(Ware.ReservationDiscount,0) as ReservationDiscount,
      ISNULL(PacketItem_New.PostForfait, 0) AS PostForfait,
      Ware.CityTax,
      ISNULL(Ware.AllowZeroPrice, 0)
    FROM Ware WITH (NOLOCK)
    INNER JOIN ACCOUNTS WITH (NOLOCK) ON  Ware.ResultAccountNumber = Accounts.AccountNumber
    INNER JOIN PacketItem_New WITH (NOLOCK) ON  Ware.WareNumber = PacketItem_New.WareNumber AND PacketItem_New.PacketNumber=@PacketNumber
    INNER JOIN ArrangementRoomXTab WITH (NOLOCK) ON ArrangementRoomXTab.PacketItemNumber = PacketItem_New.PacketItemNumber
    INNER JOIN ArrangementReservationsXTab WITH (NOLOCK) on ArrangementRoomXTab.ArrangementLineNumber = ArrangementReservationsXTab.ArrangementLineNumber
      AND ArrangementReservationsXTab.ReferenceNumber = @ReferenceNumber
      AND ((ISNULL(@GuestNumber, 0) > 0 AND ArrangementReservationsXTab.GuestNumber = @GuestNumber) OR ISNULL(@GuestNumber,0) = 0)
    INNER JOIN ArrangementLines WITH (NOLOCK) ON ArrangementReservationsXTab.ArrangementLinenumber = ArrangementLines.ArrangementLinenumber 
      AND ((@MoveFromPackageDeb = 1 AND @MoveToPackageDeb = 1 AND CONVERT(VARCHAR(8), ArrangementLines.[Date], 112) = CONVERT(VARCHAR(8), @Date, 112)) OR (@MoveFromPackageDeb = 1 AND @MoveToPackageDeb = 0) AND (CONVERT(VARCHAR(8), ArrangementLines.[Date], 112) = CONVERT(VARCHAR(8), @Date, 112) ) OR ((@MoveFromPackageDeb = 0 AND @MoveToPackageDeb = 1)) AND (CONVERT(VARCHAR(8), ArrangementLines.[Date], 112) = CONVERT(VARCHAR(8), @Date+1, 112) ))
    LEFT OUTER JOIN Departments WITH (NOLOCK) ON Departments.PK_Department = Arrangementlines.FK_PacketChargeDepartment 
    LEFT OUTER JOIN PacketItem_NewRoomTypeXtab WITH (NOLOCK) ON PacketItem_NewRoomTypeXtab.PacketItemNumber = PacketItem_New.PacketItemNumber  
    WHERE ((ISNULL(PacketItem_NewRoomTypeXtab.RoomTypeNumber,-1) = -1) OR (PacketItem_NewRoomTypeXtab.RoomTypeNumber = @RoomTypeNumber))
    AND (ISNULL(@AConferenceRoomLineNumber, 0) = 0 OR ArrangementRoomXTab.LineNumber = @AConferenceRoomLineNumber)
    AND (Ware.WareNumber <> ISNULL(@CityTaxWareNumber, 0) OR @APostCityTax = 1)

    UNION

    SELECT DISTINCT
      NULL,
      PacketItem_New.SortNumber,
      pd.FK_Department,
      Ware.ResultAccountNumber,
      Ware.BalanceAccountNumber,
      Ware.StockAccountNumber,
      Ware.WareNumber,
      PacketItem_New.PriceOverWrite,
      PacketItem_New.TextOverwrite,
      PacketItem_New.DebType,
      CASE WHEN Ware.WareNumber = @CityTaxWareNumber THEN 99999 ELSE CASE WHEN PacketItem_New.DebType IN (2,6,9) THEN 1 ELSE 0 END END AS PercentDebType,
      Accounts.VatValueNumber,
      Accounts.VATAccountNumber,
      isnull(Ware.ReservationDiscount,0) as ReservationDiscount,
      ISNULL(PacketItem_New.PostForfait, 0) AS PostForfait,
      Ware.CityTax,
      ISNULL(Ware.AllowZeroPrice, 0)
    FROM Ware WITH (NOLOCK)
    INNER JOIN ACCOUNTS WITH (NOLOCK) ON  Ware.ResultAccountNumber = Accounts.AccountNumber
    INNER JOIN PacketItem_New WITH (NOLOCK) ON  Ware.WareNumber = PacketItem_New.WareNumber AND PacketItem_New.PacketNumber=@PacketNumber
    LEFT OUTER JOIN PacketItem_NewRoomTypeXtab WITH (NOLOCK) ON PacketItem_NewRoomTypeXtab.PacketItemNumber = PacketItem_New.PacketItemNumber  
    LEFT OUTER JOIN PacketItem_NewDepartmentXTab pd WITH (NOLOCK) ON pd.PacketItemNumber = PacketItem_New.PacketItemNumber AND pd.Type = 2
    LEFT OUTER JOIN Departments d WITH (NOLOCK) ON pd.FK_Department = d.PK_Department
    WHERE ((@HotelNumber = -1) OR (ISNULL(d.HotelNumber, 0) = @HotelNumber))
    AND ((ISNULL(PacketItem_NewRoomTypeXtab.RoomTypeNumber,-1) = -1) OR (PacketItem_NewRoomTypeXtab.RoomTypeNumber = @RoomTypeNumber))
    AND PacketItem_New.Arrangement = 0
    AND (Ware.WareNumber <> ISNULL(@CityTaxWareNumber, 0) OR @APostCityTax = 1)
    ORDER BY PercentDebType, SortNumber
  
    Open #WareCur

    Fetch Next From #WareCur
    Into @ArrangementLineNumber, @SortNumber, @FK_ChargeDepartmentNumber, @ResultAccountNumber,@BalanceAccountNumber, @StockAccountNumber, @WareNumber, @WarePrice, @WareText, @DebitType, 
      @PercentDebType, @VATValueNumber, @VATAccountNumber, @ReservationDiscount, @PostForfait, @WareCityTax, @AllowZeroPrice
  END
  ELSE
  BEGIN
    Declare #WareCur Cursor  static Read_Only forward_only For
    SELECT DISTINCT
      NULL,
      PacketItem_New.SortNumber,
      Ware.ResultAccountNumber,
      Ware.BalanceAccountNumber,
      Ware.StockAccountNumber,
      Ware.WareNumber,
      PacketItem_New.PriceOverWrite,
      PacketItem_New.TextOverwrite,
      PacketItem_New.DebType,
      CASE WHEN Ware.WareNumber = @CityTaxWareNumber THEN 99999 ELSE CASE WHEN PacketItem_New.DebType IN (2,6,9) THEN 1 ELSE 0 END END AS PercentDebType,
      Accounts.VatValueNumber,
      Accounts.VATAccountNumber,
      isnull(Ware.ReservationDiscount,0) as ReservationDiscount,
      ISNULL(PacketItem_New.PostForfait, 0) AS PostForfait,
      CASE WHEN @PostProductUsePacketDepartment = 1 THEN ISNULL(dcharge.PK_Department, @DefaultPacketDepartment) ELSE NULL END,
      Ware.CityTax,
      ISNULL(Ware.AllowZeroPrice, 0)
    FROM Ware WITH (NOLOCK)
    INNER JOIN ACCOUNTS WITH (NOLOCK) ON  Ware.ResultAccountNumber = Accounts.AccountNumber
    INNER JOIN PacketItem_New WITH (NOLOCK) ON  Ware.WareNumber = PacketItem_New.WareNumber
    LEFT OUTER JOIN PacketItem_NewRoomTypeXtab WITH (NOLOCK) ON PacketItem_NewRoomTypeXtab.PacketItemNumber = PacketItem_New.PacketItemNumber  
    INNER JOIN PacketItem_NewDepartmentXTab pd WITH (NOLOCK) ON pd.PacketItemNumber = PacketItem_New.PacketItemNumber AND pd.Type = 1 -- DepartmentServiceOverwrite
    INNER JOIN Departments d WITH (NOLOCK) ON pd.FK_Department = d.PK_Department
    LEFT OUTER JOIN PacketItem_NewDepartmentXTab pdCharge WITH (NOLOCK) ON pdCharge.PacketItemNumber = PacketItem_New.PacketItemNumber AND pdCharge.Type = 2
    LEFT OUTER JOIN Departments dcharge WITH (NOLOCK) ON pdCharge.FK_Department = dCharge.PK_Department
    Where PacketItem_New.PacketNumber=@PacketNumber
    AND ((@HotelNumber = -1) OR (ISNULL(d.HotelNumber, 0) = @HotelNumber))
    AND ((ISNULL(PacketItem_NewRoomTypeXtab.RoomTypeNumber,-1) = -1) OR (PacketItem_NewRoomTypeXtab.RoomTypeNumber = @RoomTypeNumber))
    AND (Ware.WareNumber <> ISNULL(@CityTaxWareNumber, 0) OR @APostCityTax = 1)
    ORDER BY PercentDebType, SortNumber

    Open #WareCur

    Fetch Next From #WareCur
    Into @ArrangementLineNumber, @SortNumber, @ResultAccountNumber,@BalanceAccountNumber, @StockAccountNumber, @WareNumber, @WarePrice, @WareText, @DebitType, 
      @PercentDebType, @VATValueNumber, @VATAccountNumber, @ReservationDiscount, @PostForfait, @FK_ChargeDepartmentNumber, @WareCityTax, @AllowZeroPrice
  END

  Set @VatByPacketValue=0

  Select @CurrentDate = SYSTEMDATE from System WITH (NOLOCK) where Number=1

  EXEC SystemDateTime '', @RealDateTimeForTransaction OUTPUT

  if (Convert (Char(8), @Date, 112)<@CurrentDate)
    SET @DateStr = @CurrentDate
  else
    SET @DateStr = Convert (Char(8), @Date, 112)

  if ISNULL(@ChargeOnSystemDate, 0) = 0
    EXEC SystemDateTime @DateStr, @PostDateTime OUTPUT
  else
    EXEC SystemDateTime @CurrentDate, @PostDateTime OUTPUT

  IF ISNULL(@AConferenceRoomLineNumber, 0) > 0
    SET @DayProduct = 1
  If ISNULL(@DayProduct,0)=0 SET @DayProduct=0

  if (@PriceOverWritten = 0)
  begin 
    if @Print=1
    begin
      print '@ProductNumber'
      print @ProductNumber
      print '@DateStr'
      print @DateStr
      print '@RoomTypeNumber'
      print @RoomTypeNumber
      print '@Adult'
      print @Adult
      print '@Children1'
      print @Children1
      print '@Children2'
      print @Children2
    end

    --exec CalcRoomPrice @ProductNumber, @DateStr, @RoomTypeNumber, @Adult, @Children1, @Children2, @RoomPriceAdult OUTPUT, @RoomPriceChildren1 OUTPUT, @RoomPriceChildren2 OUTPUT
    --nb20190705 Replaced with function
    SELECT @RoomPriceAdult = Adult, @RoomPriceChildren1 = ChildPax1, @RoomPriceChildren2 = ChildPax2 
    FROM dbo.GetRoomPrice (@ProductNumber, @DateStr, @RoomTypeNumber, @Adult, @Children1, @Children2, -1, 0, 0, 0)

    if @Print=1
    begin
      print '@RoomPriceAdult'
      print convert(varchar(8),@RoomPriceAdult)
      print '@RoomPriceChildren1'
      print convert(varchar(8),@RoomPriceChildren1)
      print '@RoomPriceChildren2'
      print convert(varchar(8),@RoomPriceChildren2)
      print '@ArrivalAddon'
      print convert(varchar(8),@ArrivalAddon)
      print '@StayAddon'
      print convert(varchar(8),@StayAddon)
      print '@DepartureAddon'
      print convert(varchar(8),@DepartureAddon)
    end

    if @DiscountValue<>0
    begin
      SET @RoomPriceAdult = Round(@RoomPriceAdult * (1-(@DiscountValue/100)),2)
      SET @RoomPriceChildren1 = Round(@RoomPriceChildren1 * (1-(@DiscountValue/100)),2)
      SET @RoomPriceChildren2 = Round(@RoomPriceChildren2 * (1-(@DiscountValue/100)),2)
    end 
  end
  else
  begin
    SET @RoomPriceAdult = @PriceoverwriteValue
    SET @RoomPriceChildren1 = @PriceoverwriteValue
    SET @RoomPriceChildren2 = @PriceoverwriteValue
  end

  if (@FolioNumber<=0)
  begin
    if @DayProduct = 0
      Select @LogiWareNumber= WareNumber from Ware WITH (nolock) 
      INNER JOIN WareGroups WITH (Nolock) ON Ware.Waregroupnumber = WareGroups.Waregroupnumber
     where (Ware.markasdeleted is null) AND (WareGroups.payment=2) AND ((WareGroups.MarkAsDeleted is null) OR (WareGroups.MarkAsDeleted='0'))
    else 
      Select @LogiWareNumber= WareNumber from Ware WITH (nolock) 
      INNER JOIN WareGroups WITH (Nolock) ON Ware.Waregroupnumber = WareGroups.Waregroupnumber
      where (Ware.markasdeleted is null) AND (WareGroups.payment=3) AND ((WareGroups.MarkAsDeleted is null) OR (WareGroups.MarkAsDeleted='0'))
  end 

  SET @FixAmountSum = 0

  Select @PackageDebAccount= AccountNumber From Accounts WITH (nolock) where AccountType=6 AND (MarkAsDeleted='0' or MarkAsDeleted is null)

  DECLARE @FolioFound BIT
  SET @FolioFound = 0

  While (@@FETCH_STATUS <> -1)
  begin
    IF @FolioFound = 0
    BEGIN
      IF @FolioNumber <= 0
      BEGIN
        SET @AddressType = 0
        EXEC FindFolioNumber @ReferenceNumber, @ARealGuestNumber, @UserIDNumber, @LogiWareNumber, @SplitbillNumber, 1, @FolioNumber OUTPUT, @AddressType OUTPUT, NULL, @TableReservationLineNumber
      END
      ELSE
        SELECT @ReferenceNumber = ReferenceNumber, @GuestNumber = GuestNumber FROM Folios WITH (NOLOCK) WHERE FolioNumber = @FolioNumber
      SET @FolioFound = 1
    END

    IF @Print = 1
      PRINT @WareText

    IF (@ChargePacketDepartmentEnabled = 1) AND (ISNULL(@FK_ChargeDepartmentNumber, 0) <> 0) AND (ISNULL(@ReferenceNumber, 0) > 0)
      SET @FK_TurnoverDepartmentNumber = @FK_ChargeDepartmentNumber

    SELECT @HotelCustomerNumber = dbo.GetHotelCustomerNumberFromDepartment (@FK_TurnoverDepartmentNumber)

    if IsNull(@WarePrice,0)=0 
      SET  @WarePrice = 0 -- safe
    if IsNull(@DebitType,0)=0   
      Set  @DebitType = 1 -- safe

    --if @DebitType = 32767 -- CityTax
    IF @WareNumber = @CityTaxWareNumber AND @APostCityTax = 1 --Citytax
    BEGIN
      IF @Print = 1
      BEGIN
        PRINT 'Calc City Tax'
        PRINT '@ARoomTotalPrice'
        PRINT @ARoomTotalPrice
        PRINT '@CityTaxPacketTurnOver'
        PRINT @CityTaxPacketTurnOver
        PRINT '@RoomPriceAdult'
        PRINT @RoomPriceAdult
      END

      IF @DayProduct = 0
      BEGIN
        IF @WarePrice < 0 
          SET @Pieces = @NumberOfRooms*-1
       ELSE
          SET @Pieces = @NumberOfRooms
      END 

      IF @Print = 1
      BEGIN
        PRINT '@Pieces'
        PRINT @Pieces
      END

      SET @WarePrice = @ARoomTotalPrice - @CityTaxPacketTurnOver
      SET @WarePrice = @WarePrice - (@WarePrice*(1-(1/Convert(Float,((@ALogiVATValue/100.00)+1))))) -- Subtract VAT of logi

      -- subtract city tax amount
      IF @CityTaxInPercent = 1
        SET @WarePrice = @WarePrice*(1-(1/Convert(Float,((@CityTaxWarePrice/100.00)+1))))
      ELSE
        SET @WarePrice = @CityTaxWarePrice 

      SET @WarePrice = @WarePrice+(@WarePrice/100*@CityTaxVATValueWare)

--      IF @MoveFromPackageDeb = 1
--        SET @PostDatetime = DATEADD(DAY, -1, @PostDatetime)
      IF @Print = 1
      BEGIN
        PRINT '@WarePrice'
        PRINT @WarePrice
      END
    END ELSE
    --Fixed Price per room (Adult)
    if @DebitType=1
    begin
      if @Adult=0
        SET @WarePrice=0
      ELSE IF @PostHallPerGuest = 1
        SET @WarePrice = @WarePrice/@ANumberOfGuests
      SET @Pieces = 1
    end
    else
    --Price x Adult-pax
    if @DebitType=3
    begin
      if @Adult=0
      begin
        SET @WarePrice=0
        SET @Pieces = 1
      end
      else
      begin
        SET @WarePrice=@WarePrice*@Adult
        SET @Pieces = @Adult
      end
    end
    else
    --Percent of roomprice (Adult)
    if @DebitType=2
    begin
--Noget der kan håndtere at %-satsen udregnes af produkt pris +/- pakke....
     if (@DayProduct=0) OR (@DayProduct=1 AND @IsFixedPriceProduct=1)
     BEGIN
       IF @WarePrice < 0 
         SET @Pieces = @NumberOfRooms*-1
       ELSE
         SET @Pieces = @NumberOfRooms
     END 
     else
     BEGIN
       IF @NumberOfRooms < 0
         SET @Pieces = @Adult*-1
       ELSE
         SET @Pieces = @Adult
     END

      if @Adult=0
        SET @WarePrice=0
      else
      begin
        if @PackagesplitAfterReduction = 0
          SET @WarePrice=@RoomPriceAdult*(@WarePrice/100)
        else
        BEGIN
          IF @Pieces = 0
            SET @WarePrice=((@RoomPriceAdult - @FixAmountSum)*(@WarePrice/100)) - @ReductionAfterSplitSum
          ELSE
            SET @WarePrice=((@RoomPriceAdult - (@FixAmountSum / @Pieces))*(@WarePrice/100)) - @ReductionAfterSplitSum
        END

        IF @PriceOverWritten=0  
          SET @WarePrice = @WarePrice * @Pieces
      end
    end
    else
    --Fixed Price per room (Children1)
    if @DebitType=4
    begin
      SET @Pieces = 1
      if @Children1=0
        SET @WarePrice=0
      ELSE IF @PostHallPerGuest = 1
        SET @WarePrice = @WarePrice/@ANumberOfGuests
    end
    else
    --Price x Children1-pax
    if @DebitType=5
    begin
      if @Children1=0
      begin
        SET @WarePrice=0
        SET @Pieces = 1
      end
      else
      begin
        SET @WarePrice=@WarePrice*@Children1
        SET @Pieces = @Children1
      end
    end
    else
    --Percent of roomprice (Children1)
    if @DebitType=6
    begin
     if (@DayProduct=0) OR (@DayProduct=1 AND @IsFixedPriceProduct=1)
     BEGIN
       IF @WarePrice < 0 
         SET @Pieces = @NumberOfRooms*-1
       ELSE
         SET @Pieces = @NumberOfRooms
     END 
     else
     BEGIN
       IF @NumberOfRooms < 0
         SET @Pieces = @Children1 * -1
       ELSE
         SET @Pieces = @Children1
     END

     if @Children1=0
       SET @WarePrice=0
     else
     begin
       if @PackagesplitAfterReduction = 0
         SET @WarePrice=@RoomPriceChildren1*(@WarePrice/100)
       else
        BEGIN
          IF @Pieces = 0
            SET @WarePrice=((@RoomPriceChildren1 - @FixAmountSum)*(@WarePrice/100)) - @ReductionAfterSplitSum
          ELSE
            SET @WarePrice=((@RoomPriceChildren1 - (@FixAmountSum / @Pieces))*(@WarePrice/100)) - @ReductionAfterSplitSum
        END

       IF @PriceOverWritten=0  
         SET @WarePrice = @WarePrice * @Pieces
      end
    end
    else
    --Fixed Price per room (Children2)
    if @DebitType=7
    begin
      SET @Pieces = 1
      if @Children2=0
        SET @WarePrice=0
      ELSE IF @PostHallPerGuest = 1
        SET @WarePrice = @WarePrice/@ANumberOfGuests
    end
    else
    --Price x Children2-pax
    if @DebitType=8
    begin
      if @Children2=0
      begin
        SET @WarePrice=0
        SET @Pieces = 1
      end
      else
      begin
        SET @WarePrice=@WarePrice*@Children2
        SET @Pieces = @Children2
      end
    end
    else
    --Percent of roomprice (Children2)
    if @DebitType=9
    begin
     if (@DayProduct=0) OR (@DayProduct=1 AND @IsFixedPriceProduct=1)
     BEGIN
       IF @WarePrice < 0 
         SET @Pieces = @NumberOfRooms*-1
       ELSE
         SET @Pieces = @NumberOfRooms
     END 
     else
     BEGIN
       IF @NumberOfRooms < 0
         SET @Pieces = @Children2 * -1
       ELSE
         SET @Pieces = @Children2
     END

     if @Children2=0
        SET @WarePrice=0
      else
      begin
         if @PackagesplitAfterReduction = 0
           SET @WarePrice = @RoomPriceChildren2*(@WarePrice/100)
         else
         BEGIN
           IF @Pieces = 0
             SET @WarePrice = ((@RoomPriceChildren2 - @FixAmountSum)*(@WarePrice/100)) - @ReductionAfterSplitSum
           ELSE
             SET @WarePrice = ((@RoomPriceChildren2 - (@FixAmountSum / @Pieces))*(@WarePrice/100)) - @ReductionAfterSplitSum
         END

        IF @PriceOverWritten=0  
          SET @WarePrice = @WarePrice * @Pieces
      end
    end

    IF @DiscountValue > 0 
    BEGIN
      IF (@DiscountOnPackageLine = 0 AND ((@DiscountAsNettoPrice = 0) OR (@DiscountAsNettoPrice = 1 AND @ReservationDiscount = 1))) OR
        (@DiscountOnPackageLine = 1 AND @DiscountAsNettoPrice = 1 AND @ReservationDiscount = 1)
        SET @WarePrice = ROUND(@WarePrice * (1-(@DiscountValue/100)), 2)
    END

    exec GetVatvalueFromVATValueNumber @VATValueNumber, @VatValueWare OUTPUT

    if IsNull(@VatValueWare,0) = 0 SET @VatValueWare = 0

    if NOT(@DebitType in (2,6,9) AND ((@DayProduct=0) OR (@DayProduct=1 AND @IsFixedPriceProduct=1) OR (@DayProduct=1 AND @IsFixedPriceProduct=0 and @PriceOverWritten = 1)))
      SET @WarePrice = Round(convert(money,@WarePrice * @NumberOfRooms),2)
    else
      SET @WarePrice = Round(@WarePrice, 2)

    if @PackagesplitAfterReduction = 1
    Begin
      if @SubWareFromReduction = @WareNumber
        SET @ReductionAfterSplitSum = @ReductionAfterSplitSum + @WarePrice
      else if NOT(@DebitType in (2,6,9)) 
        SET @FixAmountSum = @FixAmountSum + @WarePrice
    End

    if (@NumberOfRooms<0) 
    begin
      IF @WarePrice < 0
        SET @Pieces = -1*@Pieces
      SET @WarePrice = ABS(@WarePrice)
    end
    else
    if (@WarePrice<0)
    begin
      SET @WarePrice = ABS(@WarePrice)
      SET @Pieces = -1*@Pieces
    end
    
    IF @WarePrice <> 0 OR @AllowZeroPrice = 1
    begin
      EXEC WareIsMenuWare @WareNumber, @WarePrice, @Pieces, @IsMenuWare OUTPUT
      IF @IsMenuWare = 1
      BEGIN
        SET @TotalPrice = 0
        DECLARE db_ware_cur CURSOR STATIC FOR
          SELECT w.WareName, mw.Procentage, w.ResultAccountNumber, w.BalanceAccountNumber, w.PaymentBalanceAccountNumber, w.SortNumber, w.WareNumber, Accounts.VatValueNumber, Accounts.VATAccountNumber, InPercent, mw.UseForResidualAmount
          FROM Ware w WITH (NOLOCK)          
          INNER JOIN MenuWareXTab mw WITH (NOLOCK) ON w.WareNumber = mw.WareNumber 
            AND mw.MenuNumber = @WareNumber
            AND ISNULL(w.MarkAsDeleted , 0) = 0
          INNER JOIN ACCOUNTS WITH (NOLOCK) ON w.ResultAccountNumber = Accounts.AccountNumber
          INNER JOIN MenuWare WITH (NOLOCK) ON Menuware.FK_MenuNumber = mw.MenuNumber
        OPEN db_ware_cur

        FETCH FIRST FROM db_ware_cur INTO @MenuWareName, @MenuProcentage, @MenuResultAccountNumber, @MenuBalanceAccountNumber, @MenuPaymentBalanceAccountNumber, @MenuWareSortNumber, @MenuSingleWareNumber, @MenuVatValueNumber, @MenuVATAccountNumber, @InPercent, @IsResidual
        WHILE @@FETCH_STATUS = 0
        BEGIN
          IF @MenuProcentage > 0 AND @InPercent = 0
            SET @TotalPrice = @TotalPrice + (@MenuProcentage * @Pieces)

          FETCH NEXT FROM db_ware_cur INTO @MenuWareName, @MenuProcentage, @MenuResultAccountNumber, @MenuBalanceAccountNumber, @MenuPaymentBalanceAccountNumber, @MenuWareSortNumber, @MenuSingleWareNumber, @MenuVatValueNumber, @MenuVATAccountNumber, @InPercent, @IsResidual
        END

        IF (ISNULL(@InPercent, 0) = 0) AND (@TotalPrice <> @WarePrice)
          SET @ResidualNeeded = 1
        ELSE
          SET @ResidualNeeded = 0

        FETCH FIRST FROM db_ware_cur INTO @MenuWareName, @MenuProcentage, @MenuResultAccountNumber, @MenuBalanceAccountNumber, @MenuPaymentBalanceAccountNumber, @MenuWareSortNumber, @MenuSingleWareNumber, @MenuVatValueNumber, @MenuVATAccountNumber, @InPercent, @IsResidual
          
        WHILE @@FETCH_STATUS = 0
        BEGIN
          SET @LocalPieces = @Pieces

          EXEC GetVatvalueFromVATValueNumber @MenuVatValueNumber, @MenuVatValueWare OUTPUT

          IF @InPercent = 1
            SET @MenuWarePrice = ((@WarePrice*@MenuProcentage)/100.0)
          ELSE
          BEGIN
            SET @MenuWarePrice = @MenuProcentage*@Pieces

            IF @ResidualNeeded = 1 AND @IsResidual = 1
            BEGIN
              IF @Print = 1
              BEGIN
                PRINT '@NewPrice BEFORE'
                PRINT @MenuWarePrice
              END
              SET @MenuWarePrice = @MenuWarePrice + @WarePrice - @TotalPrice
              IF @MenuWarePrice < 0
                SET @LocalPieces = @LocalPieces * -1
              SET @ResidualNeeded = 0

              IF @Print = 1
              BEGIN
                PRINT '@NewPrice AFTER'
                PRINT @MenuWarePrice
              END
            END
          END
          IF @MenuWarePrice < 0
            SET @MenuWarePrice = @MenuWarePrice * -1
            
          IF @LocalPieces>0
          BEGIN
            IF @DiscountValue > 0 AND @DiscountAsNettoPrice = 0 AND @ReservationDiscount = 1
              SET @PacketTurnOverDiscount = @PacketTurnOverDiscount + @MenuWarePrice

            SET @PacketTurnOver = @PacketTurnOver + @MenuWarePrice
            IF ISNULL(@WareCityTax, 0) = 0
              SET @CityTaxPacketTurnOver = @CityTaxPacketTurnOver + @MenuWarePrice
            IF @MoveFromPackageDeb=1 
              SET @VatOfPacket = @MenuWarePrice*(1-(1/Convert(FLOAT, ((@MenuVatValueWare/100.00)+1))))
            ELSE
              SET @VatOfPacket = 0
          END 
          ELSE
          BEGIN
            IF @DiscountValue > 0 AND @DiscountAsNettoPrice = 0 AND @ReservationDiscount = 1
              SET @PacketTurnOverDiscount = @PacketTurnOverDiscount - @MenuWarePrice

            SET @PacketTurnOver = @PacketTurnOver - @MenuWarePrice
            IF ISNULL(@WareCityTax, 0) = 0
              SET @CityTaxPacketTurnOver = @CityTaxPacketTurnOver - @MenuWarePrice
            IF @MoveFromPackageDeb=1 
              SET @VatOfPacket = ABS(-@MenuWarePrice*(1-(1/CONVERT(FLOAT, ((@MenuVatValueWare/100.00)+1)))))
            ELSE
              SET @VatOfPacket = 0
          END 

          SET @VatOfPacketTurnOver = @VatOfPacketTurnOver + @VatOfPacket

          IF @Print=1
          BEGIN
            PRINT '@MenuVatValueWare'
            PRINT @MenuVatValueWare
            PRINT '@WarePrice'
            PRINT CONVERT(VARCHAR, @WarePrice)
            PRINT '@MenuProcentage'
            PRINT @MenuProcentage
            PRINT '@MenuWarePrice'
            PRINT CONVERT(VARCHAR, @MenuWarePrice)
            PRINT '@VatOfPacket'
            PRINT CONVERT(VARCHAR, @VatOfPacket)

            PRINT '@DiscountValue'
            PRINT @DiscountValue
            PRINT '@DiscountAsNettoPrice'
            PRINT @DiscountAsNettoPrice
            PRINT '@ReservationDiscount'
            PRINT @ReservationDiscount
            PRINT '@MoveFromPackageDeb'
            PRINT @MoveFromPackageDeb
            PRINT '@PacketTurnOverDiscount'
            PRINT @PacketTurnOverDiscount
            PRINT '@ChargeDiscountAsProduct'
            PRINT @ChargeDiscountAsProduct
          END

          EXEC PostPackageLine @MoveToPackageDeb, @MoveFromPackageDeb, @UseCashDesk, @ACashDesk, @VatOfPacket, @MenuResultAccountNumber, @MenuPaymentBalanceAccountNumber, 
            @MenuVATAccountNumber, @MenuVatValueWare, @DayProduct, @PostForfait, @RealDateTimeForTransaction, @ProductNumber, @PacketNumber, 
            @Adult, @Children1, @Children2, @PostDatetime, @UserIDNumber, @FolioNumber, @Pieces, @MenuWarePrice, @CurrencyNumber, 
            @MenuSingleWareNumber, @MenuWareName, @PackageDebAccount, @FK_TurnoverDepartmentNumber, @ARealGuestNumber, @ProductWareLinkNumber, @HotelCustomerNumber, @ArrangementLineNumber, @LocalPieces

          FETCH NEXT FROM db_ware_cur INTO @MenuWareName, @MenuProcentage, @MenuResultAccountNumber, @MenuBalanceAccountNumber, @MenuPaymentBalanceAccountNumber, @MenuWareSortNumber, @MenuSingleWareNumber, @MenuVatValueNumber, @MenuVATAccountNumber, @InPercent, @IsResidual
        END
        CLOSE db_ware_cur
        DEALLOCATE db_ware_cur

        IF @DiscountOnPackageLine = 1 AND @DiscountValue > 0 AND @DiscountAsNettoPrice = 0 AND @ReservationDiscount = 1 AND @MoveToPackageDeb = 1
        BEGIN
          SET @DiscountAmount = ROUND(((@WarePrice) * (@DiscountValue/100)), 2) -- Discount always in percent. Fixed Discount not supported yet
          SET @TempStr = RTRIM(LTRIM(Str(@DiscountValue, 5, @NumOfDecimals) + ' % ' + @DiscountwareText))

          IF @ChargeDiscountAsProduct = 0  
            EXEC Postering @PostDatetime, 1, 1, 0, 0, 0, @UserIDNumber, @FolioNumber, 0, 0, 0, 0, @TempStr, 1, @DiscountAmount, @CurrencyNumber, 0, 0, 0, 0, @FK_TurnoverDepartmentNumber, @DiscountWareNumber, 0, 0, 0, 0, '', @DummyTransNrShowOnBillOnAdd OUTPUT, 
              @HotelCustomerNumber, @ProductWareLinkNumber, 0, 0, 0, 0, 0, 0, 0, @DummyOrgGT OUTPUT, @ACashDesk
          ELSE
            EXEC Postering @PostDatetime, 1, 1, 0, 0, 0, @UserIDNumber, @FolioNumber, 0, 0, 0, 0, @TempStr, 1, @DiscountAmount, @CurrencyNumber, 0, 0, 0, 0, @FK_TurnoverDepartmentNumber, @DiscountWareNumber, 0, 0, 0, 0, '', @DummyTransNrShowOnBillOnAdd OUTPUT, 
              @HotelCustomerNumber, @ProductWareLinkNumber, @WareNumber, 0, 0, 0, 0, 0, 0, @DummyOrgGT OUTPUT, @ACashDesk
        END
      END
      ELSE
      BEGIN
        if @Pieces > 0
        begin
          IF @DiscountValue > 0 AND @DiscountAsNettoPrice = 0 AND @ReservationDiscount = 1
            SET @PacketTurnOverDiscount = @PacketTurnOverDiscount + @WarePrice

          SET @PacketTurnOver = @PacketTurnOver + @WarePrice
          IF ISNULL(@WareCityTax, 0) = 0
            SET @CityTaxPacketTurnOver = @CityTaxPacketTurnOver + @WarePrice
          if @MoveFromPackageDeb=1 
            SET @VatOfPacket = @WarePrice*(1-(1/Convert(Float,((@VatValueWare/100)+1))))
          else
            SET @VatOfPacket = 0
        end 
        else
        begin
          IF @DiscountValue > 0 AND @DiscountAsNettoPrice = 0 AND @ReservationDiscount = 1
            SET @PacketTurnOverDiscount = @PacketTurnOverDiscount - @WarePrice

          SET @PacketTurnOver = @PacketTurnOver - @WarePrice
          IF ISNULL(@WareCityTax, 0) = 0
            SET @CityTaxPacketTurnOver = @CityTaxPacketTurnOver - @WarePrice
          if @MoveFromPackageDeb=1 
            SET @VatOfPacket =  ABS(-@WarePrice*(1-(1/Convert(Float,((@VatValueWare/100)+1)))))
         else
           SET @VatOfPacket = 0
        end 
        SET @VatOfPacketTurnOver = @VatOfPacketTurnOver + @VatOfPacket

        IF @Print = 1
        BEGIN
          PRINT '@DiscountValue'
          PRINT @DiscountValue
          PRINT '@DiscountAsNettoPrice'
          PRINT @DiscountAsNettoPrice
          PRINT '@ReservationDiscount'
          PRINT @ReservationDiscount
          PRINT '@MoveFromPackageDeb'
          PRINT @MoveFromPackageDeb
        END

        IF @DiscountOnPackageLine = 1 AND @DiscountValue > 0 AND @DiscountAsNettoPrice = 0 AND @ReservationDiscount = 1 AND @MoveToPackageDeb = 1
        BEGIN
          SET @DiscountAmount = ROUND(((@WarePrice) * (@DiscountValue/100)), 2) -- Discount always in percent. Fixed Discount not supported yet
          SET @TempStr = RTRIM(LTRIM(Str(@DiscountValue, 5, @NumOfDecimals) + ' % ' + @DiscountwareText))

          IF @ChargeDiscountAsProduct = 0  
            EXEC Postering @PostDatetime, 1, 1, 0, 0, 0, @UserIDNumber, @FolioNumber, 0, 0, 0, 0, @TempStr, 1, @DiscountAmount, @CurrencyNumber, 0, 0, 0, 0, @FK_TurnoverDepartmentNumber, @DiscountWareNumber, 0, 0, 0, 0, '', @DummyTransNrShowOnBillOnAdd OUTPUT, 
              @HotelCustomerNumber, @ProductWareLinkNumber, 0, 0, 0, 0, 0, 0, 0, @DummyOrgGT OUTPUT, @ACashDesk
          ELSE
            EXEC Postering @PostDatetime, 1, 1, 0, 0, 0, @UserIDNumber, @FolioNumber, 0, 0, 0, 0, @TempStr, 1, @DiscountAmount, @CurrencyNumber, 0, 0, 0, 0, @FK_TurnoverDepartmentNumber, @DiscountWareNumber, 0, 0, 0, 0, '', @DummyTransNrShowOnBillOnAdd OUTPUT, 
              @HotelCustomerNumber, @ProductWareLinkNumber, @WareNumber, 0, 0, 0, 0, 0, 0, @DummyOrgGT OUTPUT, @ACashDesk
        END

        EXEC PostPackageLine @MoveToPackageDeb, @MoveFromPackageDeb, @UseCashDesk, @ACashDesk, @VatOfPacket, @ResultAccountNumber, @BalanceAccountNumber, @VATAccountNumber, 
          @VatValueWare, @DayProduct, @PostForfait, @RealDateTimeForTransaction, @ProductNumber, @PacketNumber, 
          @Adult, @Children1, @Children2, @PostDatetime, @UserIDNumber, @FolioNumber, @Pieces, @WarePrice, @CurrencyNumber, 
          @WareNumber, @WareText, @PackageDebAccount, @FK_TurnoverDepartmentNumber, @ARealGuestNumber, @ProductWareLinkNumber, @HotelCustomerNumber, @ArrangementLineNumber
      END 
    end

    IF (@ChargePacketDepartmentEnabled = 1) AND (ISNULL(@ReferenceNumber, 0) > 0) AND (@PostAllLines = 0)
    BEGIN
      Fetch Next From #WareCur
      Into @ArrangementLineNumber, @SortNumber, @FK_ChargeDepartmentNumber, @ResultAccountNumber, @BalanceAccountNumber, @StockAccountNumber, @WareNumber, @WarePrice, @WareText, @DebitType, 
        @PercentDebType, @VATValueNumber, @VATAccountNumber, @ReservationDiscount, @PostForfait, @WareCityTax, @AllowZeroPrice
    END
    ELSE
    BEGIN
      Fetch Next From #WareCur
      Into @ArrangementLineNumber, @SortNumber, @ResultAccountNumber, @BalanceAccountNumber, @StockAccountNumber, @WareNumber, @WarePrice, @WareText, @DebitType, 
        @PercentDebType, @VATValueNumber, @VATAccountNumber, @ReservationDiscount, @PostForfait, @FK_ChargeDepartmentNumber, @WareCityTax, @AllowZeroPrice
    END
  end

  SET @PacketTurnOver = ISNULL(@PacketTurnOver, 0)
  SET @VatOfPacketTurnOver = ISNULL(@VatOfPacketTurnOver, 0)
  SET @PacketTurnOverDiscount = ISNULL(@PacketTurnOverDiscount, 0)

  Close #WareCur
  Deallocate #WareCur
end
else
begin
  SET @PacketTurnOver = 0
  SET @VatOfPacketTurnOver = 0
  SET @PacketTurnOverDiscount = 0
end

if @Print=1
begin
  print '@PacketTurnOver'
  print @PacketTurnOver
  print '@PacketTurnOverDiscount'
  print @PacketTurnOverDiscount
  PRINT 'POSTPackage END'
end