CREATE PROCEDURE DBO.ChargeDeparturePackageWhenErlyCheckout @ReferenceNumber int, @GuestNumber SmallInt, @FK_TurnoverDepartment INT as
SET NOCOUNT ON

/*
  Changes:
    KJ 20241125: Ext: Added post discount on packageline
    KJ 20240214: Added timeZone
    KJ 20170710: Ext: Name on lodging transactions setup per hotel
    KJ 20100602: Bug: Fix for "Customer/Hotel sometmies deleted"
    KJ 20081222: Added OriginalGlobalTransactionNumber
    KJ 20070410: Department rewrite
    KJ 20070212: Lock timechanged + some cleanup
    KJ 20060504: Removed @ExDepartment - not used
    nb20060207 safety CountryNumber value on transactions is needed
    KJ 20050901: Removed AccountDaily
    20050526 JP: changed to use GetNextNumber
    Rettet d. 24/06-2004 af KS: Added hotelnumber>=0 and only saleschannel in join for hotelnumber
    Ćndring d. 17/06-2004 af KS :  Wrong fetch
    Ćndring d. 17/05-2004 af KS :  Imp hotelnumber
    Ćndring d. 27/01-2004 af KS :  Imp new package
    Ćndring d. 03/02-2004 af KS :  changed department to char(1)
*/

Declare @ShowPrint bit
SET @ShowPrint = 0

if (@ShowPrint=1)
  Print 'ChargeDeparturePackageWhenErlyCheckout'

Declare @Addon float
Declare @Addon1 float

Declare  @BillTextProduct1Addon char(50)
Declare  @EnviromentFeeProduct1 money
Declare  @DepartureAddon1 money

Declare @Pieces int

Declare @VisualRoomNumber int

Declare @DummyTransNrShowOnBillOnAdd int

Declare @FirstPost Bit

Declare @BookedTypeNumber Int

Declare @RoomNumber Int
Declare @ArrivalDate Char (8)
Declare @DepartureDate Char (8)

Declare @ArrDate datetime --av 270702

Declare @Day2 SmallInt
Declare @Day3 SmallInt
Declare @Day4 SmallInt

Declare @ProductNumber  Int
Declare @ProductNumber2 Int
Declare @ProductNumber3 Int
Declare @ProductNumber4 Int

Declare @IsFixedPriceProduct  Bit

Declare @NumberOfRooms SmallInt

Declare @PriceOverwritten  Bit
Declare @PriceOverwritten2 Bit
Declare @PriceOverwritten3 Bit
Declare @PriceOverwritten4 Bit

Declare @Adults Int
Declare @Children1 Int
Declare @Children2 Int
Declare @NameListReservationPerPerson smallint
Declare @Price Money

Declare @StayStartDate DateTime
Declare @StayEndDate DateTime

Declare @CalcPriceDay Money

Declare @PacketNumber Integer
Declare @PacketNumber1 Integer

Declare @PackageTurnOver Money
Declare @VatOfPackageTurnOver Money

Declare @VatValueProduct Float
Declare @VatValueProduct1 Float

Declare @FolioNumber int

Declare @SegmentNumber Int
Declare @PointOfSaleNumber Int
Declare @GetVATFrom SmallInt

Declare @ReservationAddressNumber Integer

Declare @StayResultAccountNumber Integer
Declare @StayResultAccountNumber1 Integer

Declare @StayBalanceAccountNumber Integer
Declare @StayBalanceAccountNumber1 Integer

Declare @StayVATAccountNumber Integer
Declare @StayVATAccountNumber1 Integer

Declare @PaymentType SmallInt

Declare @TransactionDatetime DateTime

Declare @WareNumber Integer
Declare @WareNumber1 Integer

Declare @WareText  VARChar(150)
Declare @WareText1 VARChar(150)

Declare @AddressType SmallInt

Declare @StarProduct Bit

Declare @PostDayproducts Bit

Declare @PostStay Bit

Declare @NumberOfPostRoomPrDay Int

Declare @CurrentDate DATETIME
Declare @CurrentDateStr Char(8)

Declare @PostToDate DATETIME
Declare @PostFromDate  DATETIME

Declare @GetVatValueFromProduct2 Bit
Declare @GetVatValueFromProduct3 Bit
Declare @GetVatValueFromProduct4 Bit

Declare @Logi Money
Declare @VatOfLogi Money

Declare @VatValueRoomProduct1 Float

Declare @VatValueRoomProduct2 Float
Declare @VatValueRoomProduct3 Float
Declare @VatValueRoomProduct4 Float

Declare @PriceProduct1 Money

Declare @PackagePriceProduct1 Money
DECLARE @PackagePriceProduct1Discount MONEY

Declare @VatByPacketValueProduct Money
Declare @VatByPacketValueProduct1 Money

Declare @POSTProduct1 Bit

Declare @TempVatByPacketValueProduct money
Declare @TempPackagePriceProduct Money

Declare @UseInvironmentFee Bit

Declare @GlobalTransactionNumber Integer
Declare @RealDateTimeForTransaction DateTime

Declare @PostDateStr char(8)
Declare @PostDate DATETIME

Declare @SpecifiedDepartureAddOn bit
Declare @SpecifiedDepartureAddOn1 bit

Declare @BillTextProduct VARCHAR(50)
Declare @BillTextProduct1 VARCHAR(50)

Declare @SplitBillNumber int

Declare @VATProduct Bit
Declare @LogiWareIndex tinyint

Declare @TempStr varchar(50)

Declare @PostVAT bit

Declare @UseNameOnLogiTransaction bit

Declare @GuestLastName varchar(12)

Declare @ShowOnBill bit

Declare @ProductWareLinkNumber int
Declare @ProductWareLinkNumber1 int

Declare @EmptyproductPackageNumber int
Declare @NULproductPackageNumber int

Declare @HotelContryCode varchar(3)

Declare @NoDiscountOnAddon bit
Declare @NoProvisionOnAddon bit

Declare @AddonIfPriceOverwritten bit

Declare @NumberOfPostExArrPrDay int

Declare @HotelCountryNumber INT

Declare @TotalPostExDepFromArrangement money

Declare @FeeFolioNumber INT
Declare @DummyAddressType smallint

Declare @DepartureTime Char(5)

Declare @SidehouseNumber int --nbl20030129

Declare @Arr24HoursStarts char(5)

Declare @AddonPieces SmallInt

Declare @TempPriceoverwrite Bit

Declare @NumberOfChargedPackaged int
Declare @NumberOfChargedDeparturePackaged int

Declare @PostToDateStr  char(8)
Declare @PostFromDateStr  char(8)

Declare @PackageDebAccount int

Declare @DayProduct bit

Declare @UserIDNumber Int 

Declare @AllDiscountRate Float
Declare @DiscountRate Float
Declare @TotalDiscountValueForPackagesplit Float

Declare @PackagesplitAfterDiscount bit

Declare @HotelCustomerNumber Int

Declare @PaysAdults Int
Declare @PaysChildren1 Int
Declare @PaysChildren2 Int

Declare @NameListSettingReservation smallint
Declare @NameListReservationPerPersonProduct smallint

SET @DayProduct =0

Select @PackagesplitAfterDiscount = CONVERT(Bit,KeyValue) From HotelSetUp WITH (NOLOCK)  Where  SearchKey='PackageSplitAfterDiscount'
if isnull(@PackagesplitAfterDiscount,0)=0 SET @PackagesplitAfterDiscount = 0

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

Select @HotelContryCode = TextValue, @HotelCountryNumber = CONVERT(INT,KeyValue) from HotelSetUp WITH (NOLOCK)  Where  SearchKey='CountryCode'
SELECT @HotelContryCode = CountryCode FROM Countries WITH (NOLOCK) WHERE CountryNumber = @HotelCountryNumber
IF @@ROWCOUNT = 0
  SELECT TOP 1 @HotelContryCode = CountryCode, @HotelCountryNumber = CountryNumber FROM Countries WITH (NOLOCK) 

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

SET @PostToDateStr  = @CurrentDateStr
SET @PostFromDateStr = @CurrentDateStr

Select @UserIDNumber = UserIdNumber from Personel WITH (nolock) where UserTypeNumber=3 -- autoday

Select @GetVATFrom=CONVERT(INT,KeyValue) from HotelSetUp WITH (NOLOCK)  Where  SearchKey='BookkeepingReport'

Select @NameListReservationPerPerson = CONVERT(Smallint,KeyValue) from HotelSetUp WITH (NOLOCK)  Where  SearchKey='NameListReservationPerPerson'

--SET lock_timeout 5000
DECLARE @LockTimeOut INT
SET @LockTimeOut = @@LOCK_TIMEOUT
SET LOCK_TIMEOUT 5000

if @GuestNumber=0
begin
  Declare ResCur Cursor Fast_Forward Read_Only For
  SELECT
    RESERVATIONROOMLINE.BookedTypeNumber,
    RESERVATIONROOMLINE.RoomNumber,
    RESERVATIONS.MARKETSEGMENT,
    RESERVATIONS.POINTOFSALE,
    RESERVATIONS.SplitBill,
    RESERVATIONROOMLINE.ArrivalDate,
    RESERVATIONROOMLINE.DepartureDate,
    RESERVATIONROOMLINE.Adults,
    RESERVATIONROOMLINE.Children1,
    RESERVATIONROOMLINE.Children2,
    RESERVATIONROOMLINE.Adults,
    RESERVATIONROOMLINE.Children1,
    RESERVATIONROOMLINE.Children2,
    RESERVATIONROOMLINE.ProductNumber,
    RESERVATIONROOMLINE.NumberOfRooms,
    RESERVATIONS.PriceOverwritten,
    RESERVATIONS.PriceOverwritten2,
    RESERVATIONROOMLINE.Day2,
    RESERVATIONROOMLINE.ProductNumber2,
    RESERVATIONS.PriceOverwritten3,
    RESERVATIONROOMLINE.Day3,
    RESERVATIONROOMLINE.ProductNumber3,
    RESERVATIONS.PriceOverwritten4,
    RESERVATIONROOMLINE.Day4,
    RESERVATIONROOMLINE.ProductNumber4,
    0 AS SideHouseNumber,-- Guestnumber always 0
    isnull(Customer.CustomerNumber,-1) ,
    RESERVATIONROOMLINE.NameListSetting
  FROM RESERVATIONROOMLINE WITH (NOLOCK) 
  INNER JOIN RESERVATIONROOMLINEXTAB WITH (NOLOCK) ON  RESERVATIONROOMLINE.LINENUMBER = RESERVATIONROOMLINEXTAB.LineNumber 
  INNER JOIN RESERVATIONS WITH (NOLOCK) ON RESERVATIONROOMLINEXTAB.ReferenceNumber = RESERVATIONS.ReferenceNumber AND RESERVATIONROOMLINEXTAB.GuestNumber = RESERVATIONS.GuestNumber
  INNER JOIN RESERVATIONMAIN WITH (NOLOCK) ON RESERVATIONMAIN.Referencenumber =  RESERVATIONS.ReferenceNumber AND RESERVATIONS.GuestNumber=0
  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 -- SalesChannel
  WHERE ((RESERVATIONROOMLINEXTAB.ReferenceNumber=@ReferenceNumber)  AND (RESERVATIONROOMLINEXTAB.GuestNumber=@GuestNumber))
end
else
begin
  Declare ResCur Cursor Fast_Forward Read_Only For
  SELECT
    RESERVATIONROOMLINE.BookedTypeNumber,
    RESERVATIONROOMLINE.RoomNumber,
    RESERVATIONS.MARKETSEGMENT,
    RESERVATIONS.POINTOFSALE,
    RESERVATIONS.SplitBill,
    RESERVATIONS.ArrivalDate,
    RESERVATIONS.DepartureDate,
    RESERVATIONS.Adults,
    RESERVATIONS.Children1,
    RESERVATIONS.Children2,
    RESERVATIONS.PaysAdults,
    RESERVATIONS.PaysChildren1,
    RESERVATIONS.PaysChildren2,
    RESERVATIONS.ProductNumber,
    RESERVATIONROOMLINE.NumberOfRooms,
    RESERVATIONS.PriceOverwritten,
    RESERVATIONS.PriceOverwritten2,
    RESERVATIONS.Day2,
    RESERVATIONS.ProductNumber2,
    RESERVATIONS.PriceOverwritten3,
    RESERVATIONS.Day3,
    RESERVATIONS.ProductNumber3,
    RESERVATIONS.PriceOverwritten4,
    RESERVATIONS.Day4,
    RESERVATIONS.ProductNumber4,
    case reservations.guestnumber
    when 0 then 0 else case sidehouse when 1 then Rooms.SideHouseNumber else 0 end end AS SideHouseNumber, --nbl20030129
    isnull(Customer.CustomerNumber,-1) ,
    RESERVATIONROOMLINE.NameListSetting
  FROM RESERVATIONROOMLINE WITH (NOLOCK) 
  INNER JOIN RESERVATIONROOMLINEXTAB WITH (NOLOCK) ON RESERVATIONROOMLINE.LINENUMBER = RESERVATIONROOMLINEXTAB.LineNumber 
  INNER JOIN RESERVATIONS WITH (NOLOCK) ON RESERVATIONROOMLINEXTAB.ReferenceNumber = RESERVATIONS.ReferenceNumber AND RESERVATIONROOMLINEXTAB.GuestNumber = RESERVATIONS.GuestNumber 
  INNER JOIN ROOMS WITH (NOLOCK) ON RESERVATIONROOMLINE.RoomNumber = ROOMS.RoomNumber
  INNER JOIN RESERVATIONMAIN WITH (NOLOCK) ON RESERVATIONMAIN.Referencenumber =  RESERVATIONS.ReferenceNumber AND RESERVATIONS.GuestNumber=0
  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 -- SalesChannel
  WHERE ((RESERVATIONROOMLINEXTAB.ReferenceNumber=@ReferenceNumber)  AND (RESERVATIONROOMLINEXTAB.GuestNumber=@GuestNumber)) AND (RESERVATIONS.PaysAdults+RESERVATIONS.PaysChildren1+RESERVATIONS.PaysChildren2>0)
end

Open ResCur

Fetch Next From ResCur Into @BookedTypeNumber, @RoomNumber, @SegmentNumber, @PointOfSaleNumber, @SplitBillNumber, @ArrivalDate, @DepartureDate, @PaysAdults, @PaysChildren1, @PaysChildren2,
  @Adults, @Children1, @Children2, @ProductNumber, @NumberOfRooms, @PriceOverwritten, @PriceOverwritten2, @Day2, @ProductNumber2, @PriceOverwritten3, @Day3, @ProductNumber3,
  @PriceOverwritten4, @Day4, @ProductNumber4, @SidehouseNumber, @HotelCustomerNumber, @NameListSettingReservation

SET @CurrentDate = Convert(DATETIME, @CurrentDateStr)
SET @PostToDate  = Convert(DATETIME, @PostToDateStr)
SET @PostFromDate = Convert(DATETIME, @PostFromDateStr)

SET @DepartureDate = @CurrentDateStr

While (@@Fetch_Status=0)
begin
  SET @PostDateStr = @PostFromDateStr
  SET @PostDate = @PostFromDate    

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

  if (@PostDate=@DepartureDate)
  begin
    if IsNull(@SplitBillNumber,0)=0 SET @SplitBillNumber = 0
    if (@ShowPrint=1)
    begin
      print '@SplitBillNumber (ChargeDeparturePackageWhenErlyCheckout)'
      print @SplitBillNumber
    end

    SET @PaymentType = 2 -- Rooms
    if (@ShowPrint=1)
    begin
      PRINT '@PaymentType'
      PRINT @PaymentType
    end

    if @ROOMNUMBER > 0  -- TODO exchange with RoomNumberID when table has been nomalized
    begin
      if @SidehouseNumber > 0
        SELECT @VisualRoomNumber = @SidehouseNumber
      else
        SELECT @VisualRoomNumber = Number FROM Rooms WITH (NOLOCK)  WHERE RoomNumber = @ROOMNUMBER  -- TODO use primary key instead! Then select is not needed anymore!
    end
    else
      SET @VisualRoomNumber = NULL

    if IsNull(@Price,0)=0 SET @Price = 0
    if IsNull(@Day2,0)=0   Set  @Day2 = 0
    if IsNull(@Day3,0)=0   Set  @Day3 = 0
    if IsNull(@Day4,0)=0   Set  @Day4 = 0

    if ((@Day2+@Day3+@Day4)>0) 
    begin
      if @NameListSettingReservation = 1  -- 1 = per person, 2 = per room
      begin
        SET @Adults = @PaysAdults
        SET @Children1 = @PaysChildren1
        SET @Children2 = @PaysChildren2
      end

      if (@PostFromDate>=Convert(DateTime,@ArrivalDate)) AND (@PostFromDate<=Convert(DateTime,@ArrivalDate)+@Day2-1)
      begin
        if ((@PriceOverWritten=0) AND ((@ProductNumber is null) OR (@ProductNumber = 0))) 
          SET @PriceOverWritten = 1
        else if @PriceOverWritten=1 And @ProductNumber>0  
        begin 
          Select @TempPriceoverwrite = PriceOverWrite from Products WITH (nolock) where productnumber=@ProductNumber
          if @TempPriceoverwrite = 0 
              SET @PriceOverWritten=0  
        end
      end

      if (((@PostFromDate>=Convert(DateTime,@ArrivalDate)+@Day2-1) AND (@PostFromDate<=Convert(DateTime,@ArrivalDate)+@Day3-1))
         OR ((@PostToDate>=Convert(DateTime,@ArrivalDate)+@Day2-1) AND (@PostToDate<=Convert(DateTime,@ArrivalDate)+@Day3-1)))
      begin
        if ((@PriceOverWritten2=0) AND ((@ProductNumber2 is null) OR (@ProductNumber2 = 0))) 
          SET @PriceOverWritten2 = 1
        else if @PriceOverWritten2=1 And @ProductNumber2>0 
        begin
          Select @TempPriceoverwrite = PriceOverWrite from Products WITH (nolock) where productnumber=@ProductNumber2
          if @TempPriceoverwrite = 0 
            SET @PriceOverWritten2=0  
        end
      end

      if  (((@PostFromDate>=Convert(DateTime,@ArrivalDate)+@Day3-1) AND (@PostFromDate<=Convert(DateTime,@ArrivalDate)+@Day4-1))
          OR ((@PostToDate>=Convert(DateTime,@ArrivalDate)+@Day3-1) AND (@PostToDate<=Convert(DateTime,@ArrivalDate)+@Day4-1)))
      begin
        if ((@PriceOverWritten3=0) AND ((@ProductNumber3 is null) OR (@ProductNumber3 = 0))) 
          SET @PriceOverWritten3 = 1
        else if @PriceOverWritten3=1 And @ProductNumber3>0
        begin
          Select @TempPriceoverwrite = PriceOverWrite from Products WITH (nolock) where productnumber=@ProductNumber3
          if @TempPriceoverwrite = 0 
            SET @PriceOverWritten3=0  
        end
      end

      if  (((@PostFromDate>=Convert(DateTime,@ArrivalDate)+@Day4-1) AND (@PostFromDate<=Convert(DateTime,@DepartureDate)))
          OR ((@PostToDate>=Convert(DateTime,@ArrivalDate)+@Day4-1) AND (@PostToDate<=Convert(DateTime,@DepartureDate))))
      begin
        if @PriceOverWritten4=1 And @ProductNumber4>0
        begin
          Select @TempPriceoverwrite = PriceOverWrite from Products WITH (nolock) where productnumber=@ProductNumber4
          if @TempPriceoverwrite = 0 
            SET @PriceOverWritten4=0  
        end
        else if ((@PriceOverWritten4=0) AND ((@ProductNumber4 is null) OR (@ProductNumber4 = 0))) 
          SET @PriceOverWritten4 = 1
      end
    end
    else
    begin
      if ((@PriceOverWritten=0) AND ((@ProductNumber is null) OR (@ProductNumber = 0)))
        SET @PriceOverWritten = 1
      else if @PriceOverWritten=1 And @ProductNumber>0
      begin 
        Select @TempPriceoverwrite = PriceOverWrite from Products WITH (nolock) where productnumber=@ProductNumber
        if @TempPriceoverwrite = 0 
          SET @PriceOverWritten=0  
      end

      if @ProductNumber>0
        Select @NameListReservationPerPersonProduct = NameListSetting from Products WITH (nolock) where productnumber=@ProductNumber

      if  (@ProductNumber>0 AND @NameListReservationPerPersonProduct=1) OR ((@ProductNumber=0 OR @ProductNumber is null) AND @NameListReservationPerPerson=1)
      begin
        SET @Adults = @PaysAdults
        SET @Children1 = @PaysChildren1
        SET @Children2 = @PaysChildren2
      end               
    end

    if IsNull(@BookedTypeNumber,0)=0  Set @BookedTypeNumber = 0
    if IsNull(@NumberOfRooms,0)=0 SET @NumberOfRooms = 0
    if IsNull(@Adults,0)=0     Set  @Adults = 0
    if IsNull(@Children1,0)=0  Set  @Children1 = 0
    if IsNull(@Children2,0)=0  Set  @Children2 = 0

    if (@ShowPrint=1)
    begin
      Print 'GETVATFROM'
      Print @GetVATFrom
      print '@VisualRoomNumber'
      print @VisualRoomNumber
    end

    if ((@GetVATFrom>=0) AND (@GetVATFrom<3) OR (@GetVATFrom=4))
    begin
      if (@GetVATFrom=0) -- Get Vat From Segment
        exec GetVatValueAndAccountnumbers @DayProduct, @GetVatFrom, @SegmentNumber, @WareNumber1 OUTPUT, @StayBalanceAccountNumber1 OUTPUT, @StayResultAccountNumber1 OUTPUT, @StayVATAccountNumber1 OUTPUT , @VatValueProduct1 OUTPUT, @WareText1 OUTPUT
      else if (@GetVATFrom=1) -- Get Vat From POS
        exec GetVatValueAndAccountnumbers @DayProduct, @GetVatFrom, @PointOfSaleNumber, @WareNumber1 OUTPUT, @StayBalanceAccountNumber1 OUTPUT, @StayResultAccountNumber1 OUTPUT, @StayVATAccountNumber1 OUTPUT , @VatValueProduct1 OUTPUT, @WareText1 OUTPUT
      else if (@GetVATFrom=2) -- Get Vat From Roomtype -- TODO ConferenceRoom if DayProduct
        exec GetVatValueAndAccountnumbers @DayProduct, @GetVatFrom, @BookedTypeNumber, @WareNumber1 OUTPUT, @StayBalanceAccountNumber1 OUTPUT, @StayResultAccountNumber1 OUTPUT, @StayVATAccountNumber1 OUTPUT , @VatValueProduct1 OUTPUT, @WareText1 OUTPUT
      else if (@GetVATFrom=4) -- VAT
      begin
        if  @ProductNumber>0
        begin
          Select @VATProduct = ExcludeVAT 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
          SET @VATProduct = 1

        SET @LogiWareIndex = @VATProduct+1

        exec GetVatValueAndAccountnumbers @DayProduct, @GetVatFrom, @LogiWareIndex, @WareNumber1 OUTPUT, @StayBalanceAccountNumber1 OUTPUT, @StayResultAccountNumber1 OUTPUT, @StayVATAccountNumber1 OUTPUT , @VatValueProduct1 OUTPUT, @WareText1 OUTPUT
      end
    end
    else --Get Vat From Producttype
      exec GetVatValueAndAccountnumbers @DayProduct, @GetVatFrom, @ProductNumber,  @WareNumber1 OUTPUT, @StayBalanceAccountNumber1 OUTPUT, @StayResultAccountNumber1 OUTPUT, @StayVATAccountNumber1 OUTPUT , @VatValueProduct1 OUTPUT, @WareText1 OUTPUT
  end

  if (@ShowPrint=1)
  begin
    Print '@WareNumber1'
    Print  @WareNumber1
  end

  SET @AddressType = 0

  exec FindFolioNumber @ReferenceNumber, @GuestNumber, @UserIDNumber, @WareNumber1, @SplitbillNumber, 0, @FolioNumber OUTPUT, @AddressType OUTPUT

  exec GetDiscountRate @ReferenceNumber, @GuestNumber, @AddressType, 0, @AllDiscountRate output
  exec GetDiscountRate @ReferenceNumber, @GuestNumber, @AddressType, 1, @DiscountRate output

  if @PackagesplitAfterDiscount = 1
    SET @TotalDiscountValueForPackagesplit = @DiscountRate + @AllDiscountRate
  else
    SET @TotalDiscountValueForPackagesplit = 0

  if (@ShowPrint=1)
  begin
    print '@AddressType'
    print @AddressType
    print '@PostDate'
    Print Convert( Varchar(8),@PostDate,112)
  end  

  SET @FeeFolioNumber = 0

  WHILE (@PostDate=@DepartureDate)
  Begin
    -- Hvis der er forudposteret rum for denne dag, skal der ikke konteres igen!!
    SET @NumberOfPostRoomPrDay = 0

    if (@ShowPrint=1)
    begin
      print '@NumberOfPostRoomPrDay'
      print @NumberOfPostRoomPrDay
    end  

    if (@NumberOfPostRoomPrDay=0)  --der er ikke posteret ophold for denne dag!!!! --ks 9/5-2001
    begin
      SET @PackageTurnOver = 0
      SET @VatOfPackageTurnOver = 0
      SET @POSTProduct1 = 0

      if (@ShowPrint=1)
      begin
        print '@Dayproduct'
        print @Dayproduct
      end

      if ((@Day2+@Day3+@Day4)>0)
        SET @StarProduct=1
      else
        SET @StarProduct=0

      if (@StarProduct=0)
      Begin
        SET @StayStartDate = Convert (DATETIME, @ArrivalDate)
        SET @StayEndDate =  Convert (DATETIME, @DepartureDate)
        SET @POSTProduct1 = 1

        exec ProductPricesDay @ProductNumber,@StayStartDate, @StayEndDate, @PostDate, @BookedTypeNumber, @NumberOfRooms, @Adults, @Children1, @Children2, @Addon1 OUTPUT, @BillTextProduct1 OUTPUT, @BillTextProduct1Addon OUTPUT,  @PriceProduct1 OUTPUT, @PacketNumber OUTPUT, @EnviromentFeeProduct1 OUTPUT, @IsFixedPriceProduct OUTPUT, @VATProduct OUTPUT, @SpecifiedDepartureAddOn1 OUTPUT

        SET @BillTextProduct1Addon = ''
        SET @Addon1 = 0
        SET @PriceProduct1 = 0 
        SET @EnviromentFeeProduct1 = 0 
        SET @SpecifiedDepartureAddOn1 = 0
        SET @DepartureAddon1 = 0

        if (@GetVATFrom=4)
        begin
          SET @LogiWareIndex = @VATProduct+1
          exec GetVatValueAndAccountnumbers @DayProduct, @GetVatFrom, @LogiWareIndex, @WareNumber1 OUTPUT, @StayBalanceAccountNumber1 OUTPUT, @StayResultAccountNumber1 OUTPUT, @StayVATAccountNumber1 OUTPUT , @VatValueProduct1 OUTPUT, @WareText1 OUTPUT
        end

        Select @NumberOfChargedPackaged = Count(TransactionNumber) from Transactions WITH (NOLOCK) INNER JOIN PERSONEL WITH (NOLOCK) ON TRANSACTIONS.UserIDNumber = PERSONEL.UserIDNumber
        where (ProductNumber = @ProductNumber and PackageNumber = @PacketNumber) 
        AND (FolioNumber in (Select FolioNumber FROM Folios WITH (NOLOCK) where ReferenceNumber=@ReferenceNumber AND (GuestNumber=0 OR GuestNumber=@GuestNumber)))
        AND (GuestNumber=@GuestNumber) AND ((PERSONEL.UserTypeNumber = 4 AND (MovedDeleted=0)) OR ((MovedDeleted=0 OR (MovedDeleted=1 AND MovedFolioNr>0)) AND (PERSONEL.UserTypeNumber = 3))) AND /*OR (MovedDeleted=1 AND MovedFolioNr is null)) AND*/ (Convert(Char(8),OriginalDate,112)=@PostDateStr) 
        AND ((AccountNumber = @PackageDebAccount) and (Debit=1))

        if @PacketNumber>0 AND @NumberOfChargedPackaged = 0
        begin
          EXEC GetNextNumber 'PRODUCTWARELINKIDENTITY', 1, @ProductWareLinkNumber1 OUTPUT
          exec PostPackage -1, @ReferenceNumber, @GuestNumber, @SplitBillNumber,  @StayResultAccountNumber1, 1,1, @PriceOverWritten, @BookedTypeNumber, @UserIDNumber, @PacketNumber, @ProductNumber, @NumberOfRooms, @PostDate, @Adults, @Children1, @Children2, @PriceProduct1, @FK_TurnoverDepartment, @TotalDiscountValueForPackagesplit, @PackagePriceProduct1 OUTPUT, @VatByPacketValueProduct1 OUTPUT, @PackagePriceProduct1Discount OUTPUT, @ProductWareLinkNumber1, @HotelCountryNumber, @HotelCustomerNumber
        end
        else
        begin
          SET @PackagePriceProduct1 = 0
          SET @VatByPacketValueProduct1 = 0
          SET @PackagePriceProduct1Discount = 0
        end                
      end
      else -- StarProduct = 1
      begin
        IF ISNULL(@ProductNumber,0)=0 SET @ProductNumber = 0

        IF ISNULL(@ProductNumber2,0)=0 SET @ProductNumber2 = 0
        IF ISNULL(@ProductNumber3,0)=0 SET @ProductNumber3 = 0
        IF ISNULL(@ProductNumber4,0)=0 SET @ProductNumber4 = 0

        SET @POSTProduct1 = 1
        SET @StayEndDate =  @PostDate

        if (@PostDate=(Convert (DATETIME, @ArrivalDate)+@Day2-1))
        begin
          SET @StayStartDate = Convert (DATETIME, @ArrivalDate)
        end
        else if (@PostDate=(Convert(DateTime,@ArrivalDate)+@Day3-1))
        begin
          SET @StayStartDate = Convert (DATETIME, @ArrivalDate)+@Day2-1
          SET @ProductNumber = @ProductNumber2
        end
        else if (@PostDate=(Convert(DateTime,@ArrivalDate)+@Day4-1))
        begin
          SET @StayStartDate = Convert (DATETIME, @ArrivalDate)+@Day3-1
          SET @ProductNumber = @ProductNumber3
        end 
        else if (@PostDate=(Convert(DateTime,@DepartureDate)))
        begin 
          SET @StayStartDate = Convert (DATETIME, @ArrivalDate)+@Day4-1
          SET @ProductNumber = @ProductNumber4
        end

        exec ProductPricesDay @ProductNumber,@StayStartDate, @StayEndDate, @PostDate, @BookedTypeNumber, @NumberOfRooms, @Adults, @Children1, @Children2, @DepartureAddon1 OUTPUT, @BillTextProduct1 OUTPUT, @BillTextProduct1Addon OUTPUT,  @PriceProduct1 OUTPUT, @PacketNumber OUTPUT, @EnviromentFeeProduct1 OUTPUT, @IsFixedPriceProduct OUTPUT, @VATProduct OUTPUT, @SpecifiedDepartureAddOn1 OUTPUT

        SET @AddOn= 0 
        SET @PriceProduct1 = 0
        SET @EnviromentFeeProduct1 = 0
        SET @BillTextProduct1Addon = ''
        SET @SpecifiedDepartureAddOn1= 0
        SET @DepartureAddon1 = 0

        if (@GetVATFrom=4)
        begin
          SET @LogiWareIndex = @VATProduct+1
          exec GetVatValueAndAccountnumbers @DayProduct, @GetVatFrom, @LogiWareIndex, @WareNumber1 OUTPUT, @StayBalanceAccountNumber1 OUTPUT, @StayResultAccountNumber1 OUTPUT, @StayVATAccountNumber1 OUTPUT , @VatValueProduct1 OUTPUT, @WareText1 OUTPUT
        end

        Select @NumberOfChargedPackaged = Count(TransactionNumber) from Transactions WITH (NOLOCK) INNER JOIN PERSONEL WITH (NOLOCK) ON TRANSACTIONS.UserIDNumber = PERSONEL.UserIDNumber
        where (ProductNumber = @ProductNumber and PackageNumber = @PacketNumber) 
        AND (FolioNumber in (Select FolioNumber FROM Folios WITH (NOLOCK) where ReferenceNumber=@ReferenceNumber AND (GuestNumber=0 OR GuestNumber=@GuestNumber)))
        AND (GuestNumber=@GuestNumber) AND ((PERSONEL.UserTypeNumber = 4 AND (MovedDeleted=0)) OR ((MovedDeleted=0 OR (MovedDeleted=1 AND MovedFolioNr>0)) AND (PERSONEL.UserTypeNumber = 3))) AND /*OR (MovedDeleted=1 AND MovedFolioNr is null)) AND*/ (Convert(Char(8),OriginalDate,112)=@PostDateStr) 
        AND ((AccountNumber = @PackageDebAccount) and (Debit=1))

        if @PacketNumber>0 AND @NumberOfChargedPackaged = 0
        begin
           EXEC GetNextNumber 'PRODUCTWARELINKIDENTITY', 1, @ProductWareLinkNumber1 OUTPUT
           exec PostPackage -1, @ReferenceNumber, @GuestNumber, @SplitBillNumber,  @StayResultAccountNumber1, 1,1, @PriceOverWritten, @BookedTypeNumber, @UserIDNumber, @PacketNumber, @ProductNumber, @NumberOfRooms, @PostDate, @Adults, @Children1, @Children2, @PriceProduct1, @FK_TurnoverDepartment, @TotalDiscountValueForPackagesplit, @PackagePriceProduct1 OUTPUT, @VatByPacketValueProduct1 OUTPUT, @PackagePriceProduct1Discount OUTPUT, @ProductWareLinkNumber1,@HotelCountryNumber, @HotelCustomerNumber
        end
        else
        begin
          SET @PackagePriceProduct1 = 0
          SET @VatByPacketValueProduct1 = 0
          SET @PackagePriceProduct1Discount = 0
        end            
      end -- END *-product

      EXEC SystemDateTime @PostDateStr, @TransactionDatetime OUTPUT
      EXEC SystemDateTime @CurrentDateStr, @RealDateTimeForTransaction OUTPUT

      if (@POSTProduct1=1)
      Begin
        SET @WareNumber = @WareNumber1
        SET @ProductWareLinkNumber = @ProductWareLinkNumber1
        SET @StayBalanceAccountNumber = @StayBalanceAccountNumber1
        SET @StayResultAccountNumber = @StayResultAccountNumber1
        SET @StayVATAccountNumber = @StayVATAccountNumber1
        SET @VatValueProduct = @VatValueProduct1
        SET @VatByPacketValueProduct = @VatByPacketValueProduct1
        SET @CalcPriceDay = @PriceProduct1
        SET @PackageTurnOver = @PackagePriceProduct1
        SET @Logi = @CalcPriceDay  - @PackageTurnOver

        if @BillTextProduct1 = ''
          SET @WareText = @WareText1
        else
          SET @WareText = @BillTextProduct1
      end

      SET @Pieces = @NumberOfRooms

      If IsNull(@VATOfLogi,0)=0 SET @VATOfLogi = 0

      SET @PostStay = 1
      SET @FirstPost = 1

      if @CalcPriceDay<0 
      begin  
        SET @Pieces = - @Pieces 
        SET @CalcPriceDay = ABS(Round(@CalcPriceDay,2))
      end
      else 
        SET @CalcPriceDay = Round(@CalcPriceDay,2)

      SET @Logi = Round(@Logi,2)

      While (@PostStay=1)
      begin
        -- POSTERING AF OPHOLD hvis bel°b st°rre end 0
        if (@CalcPriceDay<>0 OR @Logi<>0 OR @VatOfLogi<>0)
        begin
          SET @UseNameOnLogiTransaction = CONVERT(Bit, dbo.GetHotelSetupKeyValue('NameOnLodgingTransaction', @HotelCustomerNumber))
          if IsNull(@UseNameOnLogiTransaction,1)=1 
            SET @UseNameOnLogiTransaction=1

          if (@ShowPrint=1)
          begin
            print '@UseNameOnLogiTransaction'
            print @UseNameOnLogiTransaction
            print convert(char,@Logi)
          end
                  
          if ((@Dayproduct = 0) AND (@UseNameOnLogiTransaction=1))
          begin
            Select @GuestLastName = LastName
            From ReservationAddress WITH (Nolock) 
            INNER JOIN ReservationAddressXTab WITH (NOLOCK) ON ReservationAddressXTab.AddressNumber = ReservationAddress.AddressNumber
            WHERE ReservationAddressXTab.ReferenceNumber=@ReferenceNumber AND ReservationAddressXTab.GuestNumber=@GuestNumber AND ReservationAddress.AddressType=1 -- finder navnet ps gµsten der bor ps vµrelset

            SET @WareText = @WareText +' '+@GuestLastName
          end

          SET @WareText = LTRIM(RTRIM(@WareText))
          SET @VATOfLogi = @Logi*(1-(1/Convert(Float,((@VatValueProduct/100)+1))))

          EXEC GetNextNumber 'GLOBALTRANSACTIONIDENTITY', 1, @GlobalTransactionNumber OUTPUT

          if (@Logi - @VatOfLogi)>=0
          begin
            -- Krediter opholdets pris (Produktpris - Pakkepris) ps oms¦tning (ophold) ps resultat excl moms
            if (@ShowPrint=1)
            begin
              Print '@WareNumber'
              Print  @WareNumber
            end

            INSERT INTO Transactions (GlobalTransactionNumber, OriginalGlobalTransactionNumber, RealDateTimeForTransaction, ProductNumber, PackageNumber, PAXadult, PAXChild1, PAXChild2, DateStamp, UserIDNumber, FolioNumber, Pieces, PriceOverwrite, CurrencyNumber, ShowOnBillFlag, Debit, MovedDeleted, WareNumber, TextOverwrite , Payment, AccountNumber, VATValue, FK_DepartmentNumber, Note, GuestNumber, OriginalDate,ProductWareLinkNumber, ExchangeRateOverwrite, HotelCustomerNumber)
            VALUES(@GlobalTransactionNumber, @GlobalTransactionNumber, @RealDateTimeForTransaction, @ProductNumber, @PacketNumber, @Adults, @Children1, @Children2,@TransactionDatetime,@UserIDNumber,@FolioNumber,@Pieces, (@Logi - @VatOfLogi),@HotelCountryNumber, 0, 0, 0,@WareNumber,@WareText, 0, @StayResultAccountNumber, @VatValueProduct, @FK_TurnoverDepartment, Convert(varchar,@VisualRoomNumber), @GuestNumber, @TransactionDatetime,@ProductWareLinkNumber, 1, @HotelCustomerNumber)
          end
          else
          begin
            if (@ShowPrint=1)
            begin
              Print '@WareNumber'
              Print  @WareNumber
            end

            INSERT INTO Transactions (GlobalTransactionNumber, OriginalGlobalTransactionNumber, RealDateTimeForTransaction, ProductNumber, PackageNumber, PAXadult, PAXChild1, PAXChild2, DateStamp, UserIDNumber, FolioNumber, Pieces, PriceOverwrite, CurrencyNumber, ShowOnBillFlag, Debit, MovedDeleted, WareNumber, TextOverwrite , Payment, AccountNumber, VATValue, FK_DepartmentNumber, Note, GuestNumber, OriginalDate,ProductWareLinkNumber, ExchangeRateOverwrite, HotelCustomerNumber)
            VALUES(@GlobalTransactionNumber, @GlobalTransactionNumber, @RealDateTimeForTransaction, @ProductNumber, @PacketNumber, @Adults, @Children1, @Children2,@TransactionDatetime,@UserIDNumber,@FolioNumber,-@Pieces, ABS(@Logi - @VatOfLogi),@HotelCountryNumber, 0, 1, 0,@WareNumber,@WareText, 0, @StayResultAccountNumber, @VatValueProduct, @FK_TurnoverDepartment, Convert(varchar,@VisualRoomNumber), @GuestNumber, @TransactionDatetime,@ProductWareLinkNumber, 1, @HotelCustomerNumber)
          end

          if @Pieces>=0
          begin 
            -- Debiter vare incl moms (opholdets pris) ps balancekonto KUNDENS REGNING!!!
            if @CalcPriceDay=0 
              SET @ShowOnBill = 0
            ELSE
              SET @ShowOnBill = 1

            INSERT INTO Transactions (GlobalTransactionNumber, OriginalGlobalTransactionNumber, RealDateTimeForTransaction, ProductNumber, PackageNumber, PAXadult, PAXChild1, PAXChild2, DateStamp, UserIDNumber, FolioNumber, Pieces, PriceOverwrite, CurrencyNumber, ShowOnBillFlag, Debit, MovedDeleted, WareNumber, TextOverwrite, Payment, AccountNumber, VATValue, FK_DepartmentNumber, Note, GuestNumber, OriginalDate,ProductWareLinkNumber, ExchangeRateOverwrite, HotelCustomerNumber)
            VALUES(@GlobalTransactionNumber, @GlobalTransactionNumber, @RealDateTimeForTransaction, @ProductNumber, @PacketNumber, @Adults, @Children1, @Children2,@TransactionDatetime,@UserIDNumber, @FolioNumber,@Pieces,  @CalcPriceDay,@HotelCountryNumber, @ShowOnBill, 1, 0,@WareNumber, @WareText, 0, @StayBalanceAccountNumber, @VatValueProduct, @FK_TurnoverDepartment, Convert(varchar,@VisualRoomNumber), @GuestNumber, @TransactionDatetime,@ProductWareLinkNumber, 1, @HotelCustomerNumber)
          end
          else
          begin
            -- Debiter vare incl moms (opholdets pris) ps balancekonto KUNDENS REGNING!!!
            if @CalcPriceDay=0 
              SET @ShowOnBill = 0
            ELSE
              SET @ShowOnBill = 1

            INSERT INTO Transactions (GlobalTransactionNumber, OriginalGlobalTransactionNumber, RealDateTimeForTransaction, ProductNumber, PackageNumber, PAXadult, PAXChild1, PAXChild2, DateStamp, UserIDNumber, FolioNumber, Pieces, PriceOverwrite, CurrencyNumber, ShowOnBillFlag, Debit, MovedDeleted, WareNumber, TextOverwrite, Payment, AccountNumber, VATValue, FK_DepartmentNumber, Note, GuestNumber, OriginalDate,ProductWareLinkNumber, ExchangeRateOverwrite, HotelCustomerNumber)
            VALUES(@GlobalTransactionNumber, @GlobalTransactionNumber, @RealDateTimeForTransaction, @ProductNumber, @PacketNumber, @Adults, @Children1, @Children2,@TransactionDatetime,@UserIDNumber, @FolioNumber,@Pieces,  @CalcPriceDay,@HotelCountryNumber, @ShowOnBill, 0, 0,@WareNumber, @WareText, 0, @StayBalanceAccountNumber, @VatValueProduct, @FK_TurnoverDepartment, Convert(varchar,@VisualRoomNumber), @GuestNumber, @TransactionDatetime,@ProductWareLinkNumber, 1, @HotelCustomerNumber)
          end

          if @VatOfLogi>=0
          begin
            -- Krediter momsen for opholdet ps balancen (moms)
            INSERT INTO Transactions (GlobalTransactionNumber, OriginalGlobalTransactionNumber, RealDateTimeForTransaction, ProductNumber, PackageNumber, PAXadult, PAXChild1, PAXChild2, DateStamp, UserIDNumber, FolioNumber, Pieces, PriceOverwrite, CurrencyNumber, ShowOnBillFlag, Debit, MovedDeleted, WareNumber, TextOverwrite, Payment, AccountNumber, VATValue, FK_DepartmentNumber, Note, GuestNumber, OriginalDate,ProductWareLinkNumber, ExchangeRateOverwrite, HotelCustomerNumber)
            VALUES(@GlobalTransactionNumber, @GlobalTransactionNumber, @RealDateTimeForTransaction, @ProductNumber, @PacketNumber, @Adults, @Children1, @Children2,@TransactionDatetime,@UserIDNumber,@FolioNumber,@Pieces, @VatOfLogi,@HotelCountryNumber, 0, 0, 0,@WareNumber,@WareText,0, @StayVATAccountNumber, @VatValueProduct, @FK_TurnoverDepartment, Convert(varchar,@VisualRoomNumber), @GuestNumber, @TransactionDatetime,@ProductWareLinkNumber, 1, @HotelCustomerNumber)
          end
          else
          begin
            -- Krediter momsen for opholdet ps balancen (moms)
            INSERT INTO Transactions (GlobalTransactionNumber, OriginalGlobalTransactionNumber, RealDateTimeForTransaction, ProductNumber, PackageNumber, PAXadult, PAXChild1, PAXChild2, DateStamp, UserIDNumber, FolioNumber, Pieces, PriceOverwrite, CurrencyNumber, ShowOnBillFlag, Debit, MovedDeleted, WareNumber, TextOverwrite, Payment, AccountNumber, VATValue, FK_DepartmentNumber, Note, GuestNumber, OriginalDate,ProductWareLinkNumber, ExchangeRateOverwrite, HotelCustomerNumber)
            VALUES(@GlobalTransactionNumber, @GlobalTransactionNumber, @RealDateTimeForTransaction, @ProductNumber, @PacketNumber, @Adults, @Children1, @Children2,@TransactionDatetime,@UserIDNumber,@FolioNumber,-@Pieces, ABS(@VatOfLogi),@HotelCountryNumber, 0, 1, 0,@WareNumber,@WareText,0, @StayVATAccountNumber, @VatValueProduct, @FK_TurnoverDepartment, Convert(varchar,@VisualRoomNumber), @GuestNumber, @TransactionDatetime,@ProductWareLinkNumber, 1, @HotelCustomerNumber)
          end
        end

        SET @PostStay = 0
      end
    end

    SET @PostDate = @PostDate + 1
    SET @PostDateStr = Convert (Char (8), @PostDate, 112)
  end

  Fetch Next From ResCur Into @BookedTypeNumber, @RoomNumber, @SegmentNumber, @PointOfSaleNumber, @SplitBillNumber, @ArrivalDate, @DepartureDate, @PaysAdults, @PaysChildren1, @PaysChildren2,
     @Adults, @Children1, @Children2, @ProductNumber, @NumberOfRooms, @PriceOverwritten, @PriceOverwritten2, @Day2, @ProductNumber2, @PriceOverwritten3, @Day3, @ProductNumber3,
     @PriceOverwritten4, @Day4, @ProductNumber4, @SidehouseNumber, @HotelCustomerNumber, @NameListSettingReservation
end

Close ResCur
Deallocate ResCur

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