

CREATE PROCEDURE [dbo].[API_WmsErpSyncErpToApi]	
AS 
BEGIN

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

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

  -- wybieramy zmiany
  declare @DokErpId int;

DECLARE Doc_Cursor CURSOR FOR	 
select  Id  from dbo.ApiWMSErpToImportList;
  
OPEN Doc_Cursor;
FETCH NEXT FROM Doc_Cursor INTO @DokErpId
WHILE @@FETCH_STATUS = 0
  BEGIN
	  exec [dbo].API_WMSDokCreate @DokErpId, 10, 0, @SyncId,0,0;	                            
	  FETCH NEXT FROM Doc_Cursor INTO @DokErpId
   END;
CLOSE Doc_Cursor;
DEALLOCATE Doc_Cursor;

-- Dodatkowa Dyspozycja

DECLARE Doc_Cursor CURSOR FOR	 
select ObjectId from  ApiWmsAdditionallyDocs where WmsDocumentId=0
  --and d.Id = 3148;
  ;

OPEN Doc_Cursor;
FETCH NEXT FROM Doc_Cursor INTO @DokErpId
WHILE @@FETCH_STATUS = 0
  BEGIN
	  exec [dbo].API_WMSDokCreate @DokErpId, 10, 0, @SyncId,1;	                            
	  FETCH NEXT FROM Doc_Cursor INTO @DokErpId
   END;
CLOSE Doc_Cursor;
DEALLOCATE Doc_Cursor;

-- [dbo].[ApiWmsAdditionallyDocs]


-- Anulowane

DECLARE DocC_Cursor CURSOR FOR	 
select d.Id  from dbo.DokHandlowe d where Stan=3 and 
  NOT EXISTS ( select * from dbo.[ApiSyncItems] s where s.[SchemaId] = -10 and s.ObjectType = 40 and s.[ObjectId] = d.ID and s.Status = 4);
  OPEN DocC_Cursor;
FETCH NEXT FROM DocC_Cursor INTO @DokErpId
WHILE @@FETCH_STATUS = 0
  BEGIN
	  exec [dbo].[API_WMSDokCancel] @DokErpId, 10, 0, @SyncId;	        

	  FETCH NEXT FROM DocC_Cursor INTO @DokErpId
   END;
CLOSE DocC_Cursor;
DEALLOCATE DocC_Cursor;


  --exec [dbo].API_KntUpdateErp @id;

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