

CREATE PROCEDURE [dbo].[API_WmsExtraProc]	
AS 
BEGIN
update dbo.ApiWmsDocuments set ExtId = o.order_id, Link = o.order_page
from dbo.blOrders o where ISNULL(ExtId,'')='' and o.ErpId =  dbo.ApiWmsDocuments.ErpId ;

-- CECHY!!!
-- status
INSERT INTO [dbo].[Features]
           ([Parent],[ParentType],[Name],[Lp],[DataKey],[Data])
select ErpId Parent, 'DokHandlowe' ParentType,  'WMS_Status' Name, 0 Lp, 'Wygenerowany:'+d.NumberString DataKey,
'Wygenerowany:'+d.NumberString Data from dbo.ApiWmsDocuments d where StateId=0 and 
NOT EXISTS( select * from dbo.Features f where ParentType='DokHandlowe' and Name='WMS_Status' and f.Parent = d.ErpId);

update dbo.Features set 
dbo.Features.Data = val.Data, dbo.Features.DataKey = val.DataKey
from(
select ErpId Parent, 'DokHandlowe' ParentType,  'WMS_Status' Name, 0 Lp, 'Wygenerowany:'+d.NumberString DataKey,
'Wygenerowany:'+d.NumberString Data from dbo.ApiWmsDocuments d where StateId=0) val
where val.Parent = dbo.Features.Parent and val.Name = dbo.Features.Name and val.ParentType = dbo.Features.ParentType
and val.Data<> dbo.Features.Data;

-- Magazynier
INSERT INTO [dbo].[Features]
           ([Parent],[ParentType],[Name],[Lp],[DataKey],[Data])
select ErpId Parent, 'DokHandlowe' ParentType,  'WMS_Magazynier' Name, 0 Lp, d.OperatorId DataKey,
d.OperatorId Data from dbo.ApiWmsDocuments d where StateId=0 and 
NOT EXISTS( select * from dbo.Features f where ParentType='DokHandlowe' and Name='WMS_Magazynier' and f.Parent = d.ErpId);

update dbo.Features set 
dbo.Features.Data = val.Data, dbo.Features.DataKey = val.DataKey
from(
select ErpId Parent, 'DokHandlowe' ParentType,  'WMS_Magazynier' Name, 0 Lp, d.OperatorId DataKey,
d.OperatorId Data from dbo.ApiWmsDocuments d where StateId=0) val
where val.Parent = dbo.Features.Parent and val.Name = dbo.Features.Name and val.ParentType = dbo.Features.ParentType
and val.Data<> dbo.Features.Data;


-- Operacje
-- dodaje ceche jeśli nie ma
INSERT INTO [dbo].[Features]
           ([Parent],[ParentType],[Name],[Lp],[DataKey],[Data])
select ObjectId Parent, 'Operacje' ParentType,  'WMS_Status' Name, 0 Lp, dbo.[ApiWmsOperStatus](ObjectId) DataKey,
dbo.[ApiWmsOperStatus](ObjectId) Data from dbo.ApiWmsDocuments d where ObjectType=501  and  dbo.[ApiWmsOperStatus](ObjectId)<>''
and NOT EXISTS( select * from dbo.Features f where ParentType='Operacje' and Name='WMS_Status' and f.Parent = ObjectId)
GROUP BY ObjectId


update dbo.Features set 
dbo.Features.Data = val.Data, dbo.Features.DataKey = val.DataKey
from(
select ObjectId Parent, 'Operacje' ParentType,  'WMS_Status' Name, 0 Lp, dbo.[ApiWmsOperStatus](ObjectId) DataKey,
dbo.[ApiWmsOperStatus](ObjectId) Data from dbo.ApiWmsDocuments d where ObjectType=501  and  dbo.[ApiWmsOperStatus](ObjectId)<>'' 
) val
where val.Parent = dbo.Features.Parent and val.Name = dbo.Features.Name and val.ParentType = dbo.Features.ParentType
and val.Data<> dbo.Features.Data;



END
  
  
