
/****** Object:  UserDefinedFunction [dbo].[apiCrmTaskGetModifiedStatus]    Script Date: 06.09.2021 21:17:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE FUNCTION [dbo].[apiCrmTaskGetModifiedStatus]
(
	@docId 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 = Modified from dbo.ApiCrmTasks where Id = @docId

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

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




