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

GO

------------------------------------INSERO EM EST_NF_ENT_NFE_PEND------------------------------------      
CREATE TRIGGER [dbo].[TRG_EST_NF_SAI_NFE_CANCEL_PEND_SOLIC] ON [dbo].[EST_NF_SAI_CANCEL_SOLIC] FOR INSERT AS      

begin      
	
	IF EXISTS (SELECT P.CD_EMP 
			   FROM EST_NF_SAI_NFE P
					INNER JOIN inserted I ON 
						P.CD_EMP		= I.CD_EMP
						AND P.CD_FILIAL = I.CD_FILIAL 
						AND P.CD_NF		= I.CD_NF
						AND P.C_STAT_NFE NOT IN (110,301,302))
		BEGIN 			   
			INSERT INTO EST_NF_SAI_NFE_CANCEL_PEND (CD_EMP, CD_FILIAL, CD_NF)      
				SELECT       
					t.CD_EMP,       
					t.CD_FILIAL,       
					t.CD_NF      
				FROM       
					INSERTED t 
					INNER JOIN EST_NF_SAI NF ON 
					T.CD_EMP 	= NF.CD_EMP AND 
					T.CD_FILIAL = NF.CD_FILIAL AND 
					T.CD_NF 	= NF.CD_NF       
					INNER JOIN EST_NF_SERIE sr_nf ON      
					NF.CD_EMP 			= sr_nf.CD_EMP        
					AND NF.CD_NF_SERIE 	= sr_nf.CD_NF_SERIE       
					AND sr_nf.TP_SR_NFE = 1      
					INNER JOIN EST_NF_SAI_NFE NFE ON 
					T.CD_EMP 	= NFE.CD_EMP AND 
					T.CD_FILIAL = NFE.CD_FILIAL AND 
					T.CD_NF 	= NFE.CD_NF       
				WHERE        
					NOT EXISTS (SELECT       
									CD_EMP       
									FROM       
									EST_NF_SAI_NFE_CANCEL_PEND pend      
									WHERE       
									t.CD_EMP      = pend.CD_EMP AND       
									t.CD_FILIAL   = pend.CD_FILIAL AND       
									t.CD_NF       = pend.CD_NF);   
		END
	ELSE
		BEGIN 
			INSERT INTO EST_NF_SAI_CANCEL_PEND (CD_EMP, CD_FILIAL, CD_NF, DT_CAD)
				SELECT 
					I.CD_EMP, I.CD_FILIAL, I.CD_NF, GETDATE()
				FROM INSERTED I
				
			-- Caso a nota ainda nao tenha sido validada entao delata       
			DELETE  PEND 
			FROM EST_NF_SAI_NFE_PEND PEND 
				INNER JOIN INSERTED t ON 
					T.CD_EMP 		= PEND.CD_EMP 
					AND T.CD_FILIAL = PEND.CD_FILIAL 
					AND T.CD_NF 	= PEND.CD_NF 
		END
	 
end

GO


