IF (EXISTS(Select * from sys.sysprocedure where LCase(proc_name) = LCase('FillSaleOrderLines_CheckIn')))
THEN Drop procedure FillSaleOrderLines_CheckIn
END IF

GO

create procedure DBA.FillSaleOrderLines_CheckIn( in @GuestNum integer,in @SaleOrderID integer ) 
begin
  declare @RegNo integer;
  declare @DateReg date;
  declare @Guest integer;
  declare @Room integer;
  declare @RoomName varchar(6);
  declare @NumDays integer;
  declare @Price numeric(12,4);
  declare @KodCurrency integer;
  declare @IsRest integer;
  declare @RDate date;
  declare @place integer;
  declare @StartDate date;
  declare @EndDate date;
  declare @SaleLineID integer;
  select B.RegNum,dateadd(day,B.PayedLodgings,B.DateRegDt),B.Guest,
    B.Room,R.RoomName,(B.NumLodgings-B.PayedLodgings),B.Price,B.KodCurrency, /*M*/ /*M*/
    IsRest,B.DateRegDt,B.Room into @RegNo,@DateReg,@Guest,@Room,@RoomName,@NumDays,@Price,@KodCurrency,@IsRest,@RDate,@place
    from Book as B left outer join Rooms as R on B.Room = R.RoomNum
    where B.WhoPays = @GuestNum and(B.NumLodgings-B.PayedLodgings) <> 0;
  call FillArticleLodgings(@RegNo,0,0,@place);
  for f1 as curs1 scroll cursor for
    select Name as @ArticleName,RealLodgingsNum as @RealLodgings,A.Price as @PriceInvWithDDS,Qty as @Qty,
      MaxQty as @MaxQty,MinQty as @MinQty,ZIndex as @ZIndex,TipDDS as @TipDDS,ServiceNoLodging as @ServiceNo,
      RentMonth as @RentMonth,RentYear as @RentYear,PK.NachinPlat as @NachinPlat
      from #ArticleLodgings as a //join VatRates as VR on a.TipDDS = VR.ID
        join Book as B on A.RegNum = B.RegNum
        join PriceKinds as PK on B.PriceKind = PK.PriceKind order by ZIndex asc do
    set @SaleLineID = GetCounter('SaleOrderLineID');
    insert into SaleOrderLines( Id,DocId,ItemId,Qty,SellPrice,Discount,VatRate,RowSum,ItemName,SaleLineGuid,RegQty ) 
      values( @SaleLineID,@SaleOrderID,@ServiceNo,@MaxQty,@PriceInvWithDDS*(1+(if @TipDDS = 2 then abs(bvrDDSPart) else 0 endif)),0,
      (if @TipDDS = 2 then abs(bvrDDSPart) else 0 endif),@MaxQty*@PriceInvWithDDS*(1+(if @TipDDS = 2 then abs(bvrDDSPart) else 0 endif)),
      @ArticleName,convert(varchar(50),NEWID()),@MaxQty ) ;
    if @NachinPlat = 0 then
      set @StartDate = @RDate;
      set @EndDate = dateadd(dd,@MaxQty,@RDate)
    else
      set @StartDate = '01.' || @RentMonth || '.' || @RentYear;
      set @EndDate = (DATEADD(month,1,@StartDate)-DAY(@StartDate))
    end if;
    insert into SaleOrderLines_Links( SaleLineID,Book_RegNum,StartDate,EndDate ) 
      values( @SaleLineID,@RegNo,@StartDate,@EndDate ) 
  end for;
  delete from #Articles
end