-- FARMAGOI-18552
IF EXISTS (SELECT * FROM SYS.TRIGGERS WHERE NAME  = 'TRG_EST_PROD_CD_BARRA_PMPF' )
BEGIN	
	DROP TRIGGER TRG_EST_PROD_CD_BARRA_PMPF
END 
GO 

CREATE TRIGGER TRG_EST_PROD_CD_BARRA_PMPF ON  EST_PROD_CD_BARRA 
FOR INSERT, UPDATE ,DELETE
AS 
BEGIN

 SET NOCOUNT ON
/* ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::*/ 
 
 


   DELETE FROM PMPF_CPL  
     FROM EST_PROD_PRECO_PMPF_CPL PMPF_CPL 
	      JOIN DELETED ON DELETED.CD_EMP   = PMPF_CPL.CD_EMP
					  AND DELETED.CD_BARRA = PMPF_CPL.EAN
					 -- AND DELETED.CD_PROD  = PMPF_CPL.CD_PROD 
		 JOIN INSERTED  ON DELETED.CD_EMP  =  INSERTED.CD_EMP
					  AND DELETED.CD_BARRA <> INSERTED.CD_BARRA
					  --AND DELETED.CD_PROD  =  INSERTED.CD_PROD 

    WHERE DELETED.CD_EMP = 1 
	  

/* ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::*/ 

 

-- INSERE O CD_BARRA NOVO 
	INSERT INTO EST_PROD_PRECO_PMPF_CPL ( CD_CTR, CD_EMP, CD_PROD, EAN, VLR_PMPF, LABORATORIO, APRESENTACAO ) 
 	SELECT 
			 N_ENC.CD_CTR
			,INSERTED.CD_EMP
			,INSERTED.CD_PROD
			,N_ENC.EAN
		    ,N_ENC.VLR_PMPF
			,N_ENC.LABORATORIO
			,N_ENC.APRESENTACAO
	  FROM EST_PROD_PRECO_PMPF_CPL_N_ENC N_ENC
	       JOIN EST_PROD_PRECO_PMPF ON N_ENC.CD_CTR = EST_PROD_PRECO_PMPF.CD_CTR
		   JOIN INSERTED ON N_ENC.EAN = INSERTED.CD_BARRA
	 WHERE INSERTED.CD_EMP = 1   
	   AND NOT EXISTS (SELECT * 
						 FROM EST_PROD_PRECO_PMPF_CPL CPL
						WHERE INSERTED.CD_EMP   = CPL.CD_EMP
					--	  AND INSERTED.CD_BARRA = CPL.EAN
						  AND INSERTED.CD_PROD  = CPL.CD_PROD 
					    )
						 

	DELETE FROM CPL_N_ENC
	  FROM EST_PROD_PRECO_PMPF_CPL_N_ENC CPL_N_ENC
	       JOIN EST_PROD_PRECO_PMPF_CPL ON CPL_N_ENC.EAN = EST_PROD_PRECO_PMPF_CPL.EAN
		   JOIN INSERTED ON CPL_N_ENC.EAN	= INSERTED.CD_BARRA
     WHERE INSERTED.CD_EMP = 1   
	  


END 
    