IF NOT OBJECT_ID('TRG_PDV_VD_DEV_EST_PROD_IMP_PEND_NF_ENT_ADD') IS NULL
	BEGIN 
		DROP TRIGGER TRG_PDV_VD_DEV_EST_PROD_IMP_PEND_NF_ENT_ADD
	END

GO 

CREATE TRIGGER [TRG_PDV_VD_DEV_EST_PROD_IMP_PEND_NF_ENT_ADD] ON dbo.PDV_VD_DEV_EST_PROD_IMP_EST_NF_ENT FOR DELETE AS  
BEGIN  
 
 IF EXISTS (SELECT conf.CD_EMP   
      FROM PRC_FILIAL_CONFIG conf INNER JOIN DELETED d ON  
     conf.CD_EMP   = d.CD_EMP  
     AND conf.CD_FILIAL = d.CD_FILIAL  
      WHERE conf.CD_CHAVE = 'flag_nf_devo_requis'  
     AND ISNULL(conf.VALOR, 0) = 1)  
  BEGIN  
   INSERT INTO PDV_VD_DEV_EST_PROD_IMP_PEND_NF   
    (CD_EMP, CD_FILIAL, CD_VD, CD_IMP, CD_PROD, DT_CAD, CD_IT)  
    SELECT d.CD_EMP,   
      d.CD_FILIAL,   
      d.CD_VD,   
      d.CD_IMP,   
      d.CD_PROD,   
      imp.DT_CAD,
      ISNULL(dev_imp.CD_IT,0) AS CD_IT  
    FROM DELETED d INNER JOIN EST_PROD_IMP imp ON  
      d.CD_EMP  = imp.CD_EMP  
      AND d.CD_FILIAL = imp.CD_FILIAL  
      AND d.CD_IMP = imp.CD_IMP  
      AND d.CD_PROD = imp.CD_PROD  
      INNER JOIN PDV_VD_DEV_EST_PROD_IMP dev_imp on 
      dev_imp.CD_EMP  = imp.CD_EMP  
      AND dev_imp.CD_FILIAL = imp.CD_FILIAL  
      AND dev_imp.CD_IMP = imp.CD_IMP  
      AND dev_imp.CD_PROD = imp.CD_PROD  
  END     
END  

GO

ALTER TABLE [dbo].[PDV_VD_DEV_EST_PROD_IMP_EST_NF_ENT] ENABLE TRIGGER [TRG_PDV_VD_DEV_EST_PROD_IMP_PEND_NF_ENT_ADD]
GO


