CREATE PROCEDURE [dbo].[API_TaskSyncErpToApi]	
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,'CRM',1,CURRENT_TIMESTAMP,2);

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

  -- wygaszamy wszystkie linie urządzeń które były wyeksportowane ale nie ma już ich po stronie Enova
  update dbo.ApiDeviceLines  set Modified =-2 , ReservationType=0
  where ErpId <>0 and Modified>=0
  and NOT EXISTS ( select * from dbo.UrzadzeniaUzyte uu where uu.ID= dbo.ApiDeviceLines.ErpId)

  -- 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.Zadania t where t.ID= dbo.ApiCrmTasks.ErpId)

  -- wygaszamy wszystkie linie których zadania są wygaszone
  update dbo.ApiDeviceLines  set Modified =-2 , ReservationType=0
  from dbo.ApiCrmTasks t
  where dbo.ApiDeviceLines.TaskId = t.Id and  dbo.ApiDeviceLines.Modified>=0 and t.Modified<0;
  
  -- usuwam te powiązania które już nie istnieją
  delete dbo.ApiObjectRelations where ObjectType =1 and RelObjectType=0 and 
  NOT EXISTS( select * from dbo.ApiDocuments d where RelObjectId = d.Id)


  -- wybieramy zmiany
  declare @TaskErpId int;




DECLARE Task_Cursor CURSOR FOR	 
	
   select distinct z.Id ZadId--, ci.Id HistId 
  from dbo.ChangeInfos ci
  JOIN dbo.Zadania z ON ci.SourceGuid = z.Guid 
  JOIN dbo.ApiDefinitions def On def.ErpId = Definicja and def.Behaviour = 4  and def.Type=1
  where 
  SourceTable = 'Zadania' 

 and z.DataOd>='2022-05-01'
 
  and dbo.ApiGetSec(Time)> ISNULL((select Max([SaveTS])
  from dbo.[ApiSynchronizations]
  where [ObjectType] = 1 and [SyncType] = 2 and [Status]=2 and Message='CRM'),0)-10
  
  and NOT EXISTS ( select * from dbo.ApiSyncItems where HistId = ci.Id)
  GROUP BY (z.Id);

OPEN Task_Cursor;
FETCH NEXT FROM Task_Cursor INTO @TaskErpId
WHILE @@FETCH_STATUS = 0
  BEGIN
      select @TaskErpId;
	  exec [dbo].[API_TaskUpdateErp] @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
  
