

/****** Object:  StoredProcedure [dbo].[API_KntOsobaUpdateErp]    Script Date: 2021-09-08 10:05:16 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO


CREATE PROCEDURE [dbo].[API_KntOsobaUpdateErp]
	@KntOsobaErpId AS INT
AS 
BEGIN
/*
declare @KntErpId int;
set @KntErpId = 2;
*/
-- zabezpieczenie przed pętlą czyli sprawdzenie czy 
IF (NOT EXISTS( select * from  dbo.ApiSyncItems where ObjectId = @KntOsobaErpId and ObjectType=31 and  HistId = 
(select MAX(ci.Id) 
from dbo.ChangeInfos ci JOIN dbo.KontaktyOsoby k ON  SourceTable='KontaktyOsoby' and SourceGuid= k.Guid
where k.ID = @KntOsobaErpId)))
BEGIN


UPDATE 
dbo.ApiCustomerPersons -- WITH (UPDLOCK, SERIALIZABLE) 
  SET    
     [CustPersonId] = cv.[CustPersonId]
      ,[CustId] = cv.[CustId]
      ,[CustCustId] = cv.[CustCustId]
      ,[CustLocId] = cv.[CustLocId]
      ,[CustLocLocId] = cv.[CustLocLocId]
      ,[ErpId] = cv.[ErpId]
      ,[Name] = cv.[Name]
      ,[LastName] = cv.[LastName]
      ,[Position] = cv.[Position]
      ,[Phone] = cv.[Phone]
      ,[Phone2] = cv.[Phone2]
      ,[Email] = cv.[Email]
      ,[Notes] = cv.[Notes]
      ,[VendorId] = cv.[VendorId]
      ,[TS] = cv.[TS]
    --  ,[SaveTS] = cv.[SaveTS]
      ,[DeviceUid] = cv.[DeviceUid]
      ,[State] = cv.[State]
      --,[CustErpId] = cv.[CustErpId]
      --,[CustLocErpId] =cv.[CustLocErpId]	 	 
   from (select *from  dbo.[ApiCustomerPersonsView] cc where cc.ErpId=@KntOsobaErpId) cv
  WHERE 
  dbo.ApiCustomerPersons.ErpId = cv.ErpId and 
  dbo.ApiCustomerPersons.ErpId = @KntOsobaErpId;

IF @@ROWCOUNT = 0
BEGIN
  
	--select 'trzeba dodac';  
 INSERT INTO [dbo].ApiCustomerPersons
 ([CustPersonId],[CustId],[CustCustId],[CustLocId],[CustLocLocId]
           ,[ErpId],[Name],[LastName],[Position],[Phone],[Phone2],[Email]
           ,[Notes],[VendorId],[TS],[SaveTS],[DeviceUid],[State],[CustErpId],[CustLocErpId])
select 
[CustPersonId],[CustId],[CustCustId],[CustLocId],[CustLocLocId]
           ,[ErpId],[Name],[LastName],[Position],[Phone],[Phone2],[Email]
           ,[Notes],[VendorId],CURRENT_TIMESTAMP [TS],  0 [SaveTS],[DeviceUid],[State],0 [CustErpId], 0 [CustLocErpId]
		   from dbo.[ApiCustomerPersonsView] where ErpId = @KntOsobaErpId
END

END
END
GO


