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

SET QUOTED_IDENTIFIER ON
GO


CREATE PROCEDURE [dbo].[API_KntLokalizacjaUpdateErp]
	@KntLokalizacjaErpId 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 = @KntLokalizacjaErpId and ObjectType=11 and  HistId = 
(select MAX(ci.Id) 
from dbo.ChangeInfos ci JOIN dbo.Lokalizacje k ON  SourceTable='Lokalizacje' and SourceGuid= k.Guid
where k.ID = @KntLokalizacjaErpId)))
BEGIN


UPDATE 
dbo.ApiCustomerLocations -- WITH (UPDLOCK, SERIALIZABLE) 
  SET 
  [CustLocId] = cv.[CustLocId],
  [ErpId] = cv.[ErpId],
  [CustId] = cv.[CustId],
  [CustCustId] = cv.[CustCustId],
  [OwnerId] = cv.[OwnerId],
  [OwnerCustId] = cv.[OwnerCustId],
   [Name] = cv.[Name],
   [Code] = cv.[Code],
   [AdrrZip] = cv.[AdrrZip],
   [AdrrCity] = cv.[AdrrCity],
   [AdrrStreet] = cv.[AdrrStreet],
   [AdrrNumber] = cv.[AdrrNumber],
   [AdrrAppNumber] = cv.[AdrrAppNumber],
   [AdrrCountry] = cv.[AdrrCountry],
   [vendorId] = cv.[vendorId],
   [geolat] = cv.[geolat],
   [geolong] = cv.[geolong],
  -- [Type] = cv.[Type],
   [Phone] = cv.[Phone],
   [Phone2] = cv.[Phone2],
   [Email] = cv.[Email],
   [Notes] = cv.[Notes],
 --  [EAN] = cv.[EAN],
   [TS] = cv.TS,
   [WWW] = cv.[WWW],
   [State] = cv.[State]
	   
 	 
   from (select *from  dbo.[ApiCustomerLocationView] cc where cc.ErpId=@KntLokalizacjaErpId) cv
  WHERE 
  dbo.ApiCustomerLocations.ErpId = cv.ErpId and 
  dbo.ApiCustomerLocations.ErpId = @KntLokalizacjaErpId;

IF @@ROWCOUNT = 0
BEGIN
  
	--select 'trzeba dodac';  
 INSERT INTO [dbo].ApiCustomerLocations
 ([CustLocId],[ErpId],[CustId],[CustCustId],[OwnerId],[OwnerCustId]
      ,[Name],[Code],[AdrrZip],[AdrrCity],[AdrrStreet],[AdrrNumber],[AdrrAppNumber],[AdrrCountry]
      ,[vendorId],[geolat],[geolong]
      ,[Phone],[Phone2],[Email],[Notes],[TS],[WWW],[SaveTS],[DeviceUid],[State])
select 
[CustLocId],[ErpId],[CustId],[CustCustId],[OwnerId],[OwnerCustId]
      ,[Name],[Code],[AdrrZip],[AdrrCity],[AdrrStreet],[AdrrNumber],[AdrrAppNumber],[AdrrCountry]
      ,[vendorId],[geolat],[geolong]
      ,[Phone],[Phone2],[Email],[Notes],CURRENT_TIMESTAMP [TS],[WWW],0 [SaveTS],[DeviceUid],[State]
       from dbo.[ApiCustomerLocationView] where ErpId = @KntLokalizacjaErpId
END

END
END
GO


