
/****** Object:  StoredProcedure [dbo].[API_KntFeaturesSyncErpToApi]    Script Date: 2021-09-08 10:14:42 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

--exec [dbo].[API_KntFeaturesSyncErpToApi]	

CREATE PROCEDURE [dbo].[API_KntFeaturesSyncErpToApi]	
AS 
BEGIN
declare @LastTS int;
set @LastTS  = 
ISNULL((select MAX( [SaveTS]) - 100 from dbo.ApiSynchronizations where ObjectType = 903 and SyncType = 2),0);


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

  set @SyncId = (SELECT SCOPE_IDENTITY());

-- dodajemy to czego nie ma
INSERT INTO [dbo].[ApiFeatures]
([ErpId],[Value],[Name],[FeatureDefId],[ParentId],[ParentDbId],[GrandParentId],[ParentType],[VendorId],[TS],[Status])
select [ErpId],[Value],[Name],[FeatureDefId],[ParentId],[ParentDbId],[GrandParentId],[ParentType],[VendorId],[TS],[Status]
from [dbo].[ApiCustomerFeaturesView]  fv
where NOT EXISTS (
select * from  dbo.ApiFeatures f 
where f.Name = fv.Name and f.FeatureDefId = fv.FeatureDefId and f.ParentId = fv.ParentId
)

-- modyfikujemy to co jest 
UPDATE [dbo].[ApiFeatures]
   SET 
       [Value] = dbo.[ApiCustomerFeaturesView].[Value]
      ,[VendorId] = dbo.[ApiCustomerFeaturesView].VendorId
      ,[TS] = CURRENT_TIMESTAMP
      ,[Status] =0
   from dbo.[ApiCustomerFeaturesView] 
  WHERE 
  dbo.[ApiCustomerFeaturesView].[ParentId] = dbo.[ApiFeatures].[ParentId]
  and dbo.[ApiCustomerFeaturesView].[Name] = dbo.[ApiFeatures].[Name]
  and dbo.[ApiCustomerFeaturesView].TS > dbo.ApiFeatures.TS
  and [dbo].[ApiGetSec](dbo.[ApiCustomerFeaturesView].TS) > @LastTS;

  --select * from dbo.[ApiCustomerFeaturesView] ORDER BY TS DESC

-- usuwam to co jest 
update dbo.ApiSynchronizations set Status = 2 where Id = @SyncId;
END
GO


