
IF  EXISTS (SELECT * FROM sys.triggers WHERE object_id = OBJECT_ID(N'[dbo].[TRG_EST_NF_ENT_IT_CST_PIS_COFINS_FORN]'))
	DROP TRIGGER [dbo].[TRG_EST_NF_ENT_IT_CST_PIS_COFINS_FORN]
GO

CREATE TRIGGER [dbo].[TRG_EST_NF_ENT_IT_CST_PIS_COFINS_FORN]   ON [dbo].[EST_NF_ENT_IT]
FOR INSERT  
AS 

	UPDATE IT
		SET
			CST_PIS       = ISNULL(UFD.CD_CST_PIS, 0), 
			VLR_BASE_PIS  = ISNULL(UFD.VLR_BASE_PIS, 0),
			PERC_ALIQ_PIS  = ISNULL(UFD.PERC_PIS, 0), 
			VLR_PIS       = ISNULL(UFD.VLR_PIS, 0),

			CST_COFINS       = ISNULL(UFD.CD_CST_COFINS, 0), 
			VLR_BASE_COFINS  = ISNULL(UFD.VLR_BASE_COFINS, 0),
			PERC_ALIQ_COFINS  = ISNULL(UFD.PERC_COFINS, 0), 
			VLR_COFINS       = ISNULL(UFD.VLR_COFINS, 0) 
 
	 FROM INSERTED INS INNER JOIN  EST_NF_ENT_IT IT ON 
	 INS.CD_EMP =  IT.CD_EMP
	 AND INS.CD_FILIAL =  IT.CD_FILIAL
	 AND INS.CD_NF =  IT.CD_NF
	 AND INS.CD_PROD =  IT.CD_PROD
	 
	 INNER JOIN EST_PROD P ON 
		P.CD_EMP = IT.CD_EMP 
		AND P.CD_PROD = IT.CD_PROD
		INNER JOIN EST_NF_ENT NF ON
		IT.CD_EMP = NF.CD_EMP
		AND IT.CD_FILIAL = NF.CD_FILIAL
		AND IT.CD_NF = NF.CD_NF
		INNER JOIN  EST_PROD_NCM_FORN_PG_FORN  F ON
		NF.CD_EMP = F.CD_EMP
		AND NF.CD_FORN = F.CD_FORN
		INNER JOIN EST_PROD_NCM_FORN_GLB_MOV M ON 
		NF.CD_NT_MOV = M.CD_MOV_OP
		AND M.CD_CTR = F.CD_CTR
		INNER JOIN EST_PROD_NCM_FORN_NR_NCM NCM ON 
		P.NR_NCM COLLATE DATABASE_DEFAULT = NCM.NR_NCM COLLATE DATABASE_DEFAULT
		INNER JOIN PRC_FILIAL FIL ON 
		 NF.CD_EMP = FIL.CD_EMP 
		AND NF.CD_FILIAL= FIL.CD_FILIAL
		AND NCM.CD_CTR = F.CD_CTR
		OUTER APPLY UFD_EST_PROD_TRIB_PIS_COFINS (NF.CD_EMP, NF.CD_FILIAL, 
					   NF.CD_NT_MOV,IT.CD_PROD,IT.CD_NT_OP,IT.VLR_TOT_IT,FIL.REGIME_TRIBUTARIO,
					   NF.CD_NF,0,0) UFD	              
 		WHERE F.CD_EMP = 1
		  AND F.CD_CST_PIS_COFINS > 0 
		  AND F.CD_CST_PIS_COFINS <> INS.CST_PIS

GO