CREATE PROCEDURE dbo.GetProvisionRateNEW @AReferenceNumber INT, @AGuestNumber INT, @ASplitBillNumber INT, @AUserIdNumber INT, @AProvisionRate FLOAT OUTPUT AS
/*
  Created by Kent Johansen march 2015
  Changes:
    RN 20190828: Renames procedure due to weird issue with SörÅkers Herrgård
    KJ 20150330: Bug: Fix for "Lock request timeout when creating new reservation"
*/

SET NOCOUNT ON

DECLARE @ProvisionWareNumber INT
DECLARE @AddressType INT
DECLARE @GuestType INT

SELECT @ProvisionWareNumber = Ware.WareNumber 
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.MarkAsDeleted IS NULL 
AND Ware.Type = 10 

Select @GuestType = GuestType 
from SplitBillWareGroupXTab WITH (NOLOCK) 
where SplitBillNumber = @ASplitBillNumber 
AND WareGroupNumber in (Select WareGroupNumber From Ware WITH (NOLOCK) where WareNumber=@ProvisionWareNumber)
IF ISNULL(@GuestType, 1) = 1 
  SET @GuestType = 1 -- Safe if not marked - guest pay

IF (@GuestType in (2,4,6,8))
BEGIN
  SET @AGuestNumber=0
  SET @AddressType = (@GuestType/2)
END
ELSE
BEGIN
  IF @GuestType=1
    SET @AddressType = 1
  ELSE IF @GuestType=3
    SET @AddressType = 2
  ELSE IF @GuestType=5
    SET @AddressType = 3
  ELSE IF @GuestType=7
    SET @AddressType = 4
END

SELECT @AProvisionRate = ReservationAddress.ProvisionRate
FROM ReservationAddress WITH (NOLOCK)
INNER JOIN ReservationAddressXTab WITH (NOLOCK) ON ReservationAddressXTab.AddressNumber = ReservationAddress.AddressNumber
  AND ReservationAddressXTab.ReferenceNumber = @AReferenceNumber 
  AND ReservationAddressXTab.GuestNumber IN (@AGuestNumber, 0)
WHERE ReservationAddress.ProvisionType=3 
AND ReservationAddress.AddressType = @AddressType