
/****** Object:  UserDefinedFunction [dbo].[apiLocationModifiedStatus]    Script Date: 07.09.2021 06:17:31 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE FUNCTION [dbo].[apiLocationModifiedStatus]
(
	@Id int	
)
RETURNS  int
BEGIN
 

  declare @mojTS int;
  declare @innychTS int;
  declare @erpTS int;
  declare @mojModified int;

  declare  @ErpId int;

  select @mojTS = SaveTS, @ErpId = ErpId , @mojModified = [State] from dbo.ApiCustomerLocations where Id = @Id

  --exec [dbo].[API_MarkCRMWFVeryfication] @OrgId,@NewId,@NumerPelny;
  set @innychTS = ISNULL((
  select top 1 inny.SaveTS  from dbo.ApiCustomerLocations badany
  JOIN  dbo.ApiCustomerLocations inny ON 
   badany.VendorId = inny.VendorId 
  
  and badany.SaveTS< inny.SaveTS
  and badany.ErpId = inny.ErpId
  
  and ISNULL(badany.DeviceUid,'') = ISNULL(inny.DeviceUid,'')
  and inny.State in (1,-1)
  and (badany.ErpId<>0 OR (badany.ErpId=0 and badany.CustLocId = inny.CustLocId))
  where   
   badany.Id = @Id
   ORDER BY inny.SaveTS DESC),0);

   IF(@ErpId <>0) 
   BEGIN
	select @erpTS = dbo.ApiGetTSSec('Lokalizacje',Guid) from dbo.Lokalizacje where Id  = @ErpId;
   END
   ELSE
   BEGIN
   set @erpTS = 0;
   END

 --  select @mojTS 'Moj', @innychTS 'inny', @erpTS 'ERP'

   declare @res int;
   set @res =  case when( @mojTS> @innychTS and @mojTS> @erpTS) then @mojModified
   else case when(@innychTS<@erpTS) then 99 else 100 end end

 --  select @res;


	 return @res;
END




