

CREATE PROCEDURE [dbo].[API_DocsSyncErpToApi]	
AS 
BEGIN

declare @SyncId int;
INSERT INTO [dbo].[ApiSynchronizations] 
   ([SaveTS],[SchemaId],[ObjectType],[OperatorId],[Message],[Status],[TS],[SyncType]) 
             VALUES 
  ([dbo].[ApiGetSec](CURRENT_TIMESTAMP),-1, 0,-1,'DOCS',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
 


  -- wybieramy zmiany
  declare @DokErpId int;




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

 and z.Data>='2022-05-01'
 
  and dbo.ApiGetSec(Time)> ISNULL((select Max([SaveTS])
  from dbo.[ApiSynchronizations]
  where [ObjectType] = 0 and [SyncType] = 2 and [Status]=2 and Message='DOCS'),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 @DokErpId
WHILE @@FETCH_STATUS = 0
  BEGIN
      select @DokErpId;
	  exec [dbo].[API_DokUpdateErp] @DokErpId;
	  FETCH NEXT FROM Task_Cursor INTO @DokErpId
   END;
CLOSE Task_Cursor;
DEALLOCATE Task_Cursor;

  --exec [dbo].API_KntUpdateErp @id;

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