
/****** Object:  UserDefinedFunction [dbo].[apiCustomerModifiedStatus]    Script Date: 06.09.2021 21:19:08 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE FUNCTION [dbo].[apiCustomerModifiedStatus]
(
	@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.ApiCustomers where Id = @Id

  --exec [dbo].[API_MarkCRMWFVeryfication] @OrgId,@NewId,@NumerPelny;
  set @innychTS = ISNULL((
  select top 1 inny.SaveTS  from dbo.ApiCustomers badany
  JOIN  dbo.ApiCustomers 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.CustId = inny.CustId))
  where   
   badany.Id = @Id
   ORDER BY inny.SaveTS DESC),0);

   IF(@ErpId <>0) 
   BEGIN
	select @erpTS = dbo.ApiGetTSSec('Kontrahenci',Guid) from dbo.Kontrahenci 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




