CREATE PROCEDURE dbo.ApiWMSPreProc as
BEGIN

update dbo.ApiProdActivities set ErpId =ActErpId
from(
select dbo.ApiProdActivities.Id ActId,  ProdHistAkcja.Parent ActErpId from dbo.ApiProdActivities JOIN
 dbo.Features  idPoz ON  idPoz.Name = 'ExtId' and idPoz.ParentType ='PozycjeDokHan'  and idPoz.Lp=0 and dbo.ApiProdActivities.Id = idPOz.Data
 JOIN dbo.PozycjeDokHan poz ON idPoz.Parent = poz.ID and poz.Dokument = -dbo.ApiProdActivities.ErpId
 JOIN dbo.DokHandlowe dok ON poz.Dokument = dok.ID
 JOIN dbo.Features ProdHistAkcja ON 
 ProdHistAkcja.Name='ProdAkcja' and ProdHistAkcja.ParentType ='ProdHistorie' and  ProdHistAkcja.Data = dok.Guid 
 and ProdHistAkcja.Lp=0
  JOIN dbo.Features ProdHistPozIdent ON ProdHistPozIdent.Name= 'ProdAkcjaIdent' and 
  ProdHistPozIdent.ParentType ='ProdHistorie' and  ProdHistPozIdent.Data = poz.Ident 
  and ProdHistPozIdent.Lp=0 and ProdHistPozIdent.Parent = ProdHistAkcja.Parent
 where  dbo.ApiProdActivities.ErpId<0
 ) tab  where ActId = dbo.ApiProdActivities.Id;

update dbo.ApiWmsDocLines set ErpId = dbo.ApiProdActivities.ErpId from dbo.ApiProdActivities, dbo.ApiWmsDocuments
where dbo.ApiWmsDocLines.ErpId =  -dbo.ApiProdActivities.Id and  dbo.ApiProdActivities.ErpId>0
and dbo.ApiWmsDocLines.ErpId <0 
and dbo.ApiWmsDocLines.DocumentId = dbo.ApiWmsDocuments.Id and dbo.ApiWmsDocuments.ObjectType =502;
END
