IF EXISTS ( SELECT * FROM SYS.TRIGGERS WHERE NAME = 'TRG_EST_NF_SAI_NFE_EST_NF_SAI_NFE_AUT_PBM' )
BEGIN
	DROP TRIGGER TRG_EST_NF_SAI_NFE_EST_NF_SAI_NFE_AUT_PBM
END
GO

CREATE TRIGGER   TRG_EST_NF_SAI_NFE_EST_NF_SAI_NFE_AUT_PBM  ON  EST_NF_SAI_NFE 
FOR INSERT
AS

INSERT INTO EST_NF_SAI_NFE_AUT_PBM (CD_EMP
								   ,CD_FILIAL
								   ,CD_NF
								   ,STS_AUT_PBM
								   ,TP_PBM
								   ,OPERADORA_SELECAO
								   ,NOME_OPERADOR
								   ,NR_AUTR_PBM)
SELECT	 EST_NF_SAI.CD_EMP
		,EST_NF_SAI.CD_FILIAL
		,EST_NF_SAI.CD_NF
		,0 AS STS_AUTR_PBM
		,TELE_ORC.TIPO_PBM
		,1 AS OPERADORA_SELECAO
		,GLB_USU.NM_USU
		,TELE_ORC.NR_AUTR_PBM
   FROM TELE_ORC
		INNER JOIN TELE_ORC_EST_PED_VD ON TELE_ORC.CD_ORC = TELE_ORC_EST_PED_VD.CD_ORC
		INNER JOIN EST_PED_VD ON TELE_ORC_EST_PED_VD.CD_EMP = EST_PED_VD.CD_EMP
							 AND TELE_ORC_EST_PED_VD.CD_FILIAL = EST_PED_VD.CD_FILIAL
							 AND TELE_ORC_EST_PED_VD.CD_PED = EST_PED_VD.CD_PED
		INNER JOIN EST_NF_SAI_PED_VD ON EST_PED_VD.CD_EMP = EST_NF_SAI_PED_VD.CD_EMP
									AND EST_PED_VD.CD_FILIAL = EST_NF_SAI_PED_VD.CD_FILIAL
									AND EST_PED_VD.CD_PED = EST_NF_SAI_PED_VD.CD_PED
		INNER JOIN EST_NF_SAI ON EST_NF_SAI_PED_VD.CD_EMP = EST_NF_SAI.CD_EMP
							 AND EST_NF_SAI_PED_VD.CD_FILIAL = EST_NF_SAI.CD_FILIAL
							 AND EST_NF_SAI_PED_VD.CD_NF = EST_NF_SAI.CD_NF
		INNER JOIN GLB_USU ON TELE_ORC.CD_USU = GLB_USU.CD_USU
		INNER JOIN INSERTED I ON EST_NF_SAI.CD_EMP = I.CD_EMP
							 AND EST_NF_SAI.CD_FILIAL = I.CD_FILIAL
							 AND EST_NF_SAI.CD_NF = I.CD_NF
  WHERE TELE_ORC.TIPO_PBM = 4 
    AND NOT EXISTS ( SELECT CD_EMP
		               FROM EST_NF_SAI_NFE_AUT_PBM
		              WHERE CD_EMP		= I.CD_EMP
						AND CD_FILIAL	= I.CD_FILIAL
						AND CD_NF		= I.CD_NF )
