
/****** Object:  StoredProcedure [dbo].[API_TaskMeetinySyncErpToApi]    Script Date: 2021-09-08 09:58:26 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO


CREATE PROCEDURE [dbo].[API_TaskMeetinySyncErpToApi]	
AS 
BEGIN

declare @SyncId int;
INSERT INTO [dbo].[ApiSynchronizations] 
   ([SaveTS],[SchemaId],[ObjectType],[OperatorId],[Message],[Status],[TS],[SyncType]) 
             VALUES 
  ([dbo].[ApiGetSec](CURRENT_TIMESTAMP),-1, 1,-1,'MEETING',1,CURRENT_TIMESTAMP,2);

  set @SyncId = (SELECT SCOPE_IDENTITY());
  --select @SyncId;

 
  -- wygaszamy wszystkie zlecenia które były wyeksportowane ale już ich nie ma w Enova
  update dbo.ApiCrmTasks set Modified =-2 
  where ErpId <>0 and  Modified>=0
  and NOT EXISTS ( select * from dbo.Tuples t where t.ID= dbo.ApiCrmTasks.ErpId)


  -- wybieramy zmiany
  declare @TaskErpId int;

DECLARE Task_Cursor CURSOR FOR	 
	
   select z.Id ZadId--, ci.Id HistId 
  from dbo.ChangeInfos ci
  JOIN dbo.Tuples z ON ci.SourceGuid = z.Guid where 
  SourceTable = 'Tuples' and Definicja =24
  
  and dbo.ApiGetSec(Time)> ISNULL((select Max([SaveTS]) from dbo.[ApiSynchronizations] where [ObjectType] = 1 and [SyncType] = 2 and [Status]=2 and Message='MEETING'),0)-10
  and NOT EXISTS ( select * from dbo.ApiSyncItems where HistId = ci.Id);
  

OPEN Task_Cursor;
FETCH NEXT FROM Task_Cursor INTO @TaskErpId
WHILE @@FETCH_STATUS = 0
  BEGIN
	  exec [dbo].[API_TaskMeetingUpdateErp] @TaskErpId;
	  FETCH NEXT FROM Task_Cursor INTO @TaskErpId
   END;
CLOSE Task_Cursor;
DEALLOCATE Task_Cursor;



  --exec [dbo].API_KntUpdateErp @id;

  -- konczenie synchronizacji
  update dbo.ApiSynchronizations set Status = 2 where Id = @SyncId;
END
  
GO


