IF  EXISTS ( SELECT *
			   FROM SYS.PROCEDURES
		      WHERE NAME = 'P_AJUSTA_NFE'
		)
BEGIN
	DROP PROCEDURE P_AJUSTA_NFE
END
GO
/*
=======================================================================================
'Nível Classificação.: INFORMAÇÃO RESTRITA
'Versão..............: 20220318
'Job.................:  
'Nome................: P_AJUSTA_NFE 
'Objetivo............: Alterar Status da NFE 
'Tabelas.............: EST_NF_ENT_EST_NF_NFE_INU | EST_NF_NFE_INU_PEND | EST_NF_NFE_INU | EST_NFE_LOTE_INU_ERR
'Dt Criação..........: 18/03/2022
'Criado por..........: Eduardo Costa Moraes
'Dt Ult Alteracão....: 18/03/2022
'Alterado por........: Marcos Barros

'=======================================================================================
-- FARMAGOI-10692 - Tag #A001 - Alteração do codigo  - Tag #I001 - Inclusão de novo codigo 
-- FARMAGOI-28185 - retornar a nota para ativa quando a mesma estiver com status de Denegada

*/


CREATE PROCEDURE [DBO].[P_AJUSTA_NFE] (@CD_EMP INT
									  ,@CD_FILIAL INT
									  ,@CD_NF INT
									  ,@TIPO VARCHAR(1) 	)
AS
BEGIN
	DECLARE @CD_INU INT;

	IF @TIPO = 'S'
	BEGIN
		UPDATE EST_NF_SAI
		   SET STS_NF = 0
		 WHERE CD_EMP = 1
		   AND CD_FILIAL = @CD_FILIAL
		   AND CD_NF = @CD_NF
		   AND STS_NF IN (1,3);

		SET @CD_INU = (SELECT I.CD_INU
						 FROM EST_NF_NFE_INU I
							  INNER JOIN EST_NF_SAI_EST_NF_NFE_INU L ON I.CD_EMP = L.CD_EMP
																	AND I.CD_FILIAL = L.CD_FILIAL
																	AND I.CD_INU = L.CD_INU
						WHERE I.CD_EMP = 1
						  AND I.CD_FILIAL = @CD_FILIAL
						  AND L.CD_NF = @CD_NF );

		EXEC P_NFE_REINSERIR_PENDENCIA_EMISSAO 'S' ,1 ,@CD_FILIAL ,0 ,@CD_NF;
		
		DELETE
		  FROM EST_NF_SAI_EST_NF_NFE_INU
		 WHERE CD_INU = @CD_INU;
	END

	IF @TIPO = 'E'
	BEGIN
		UPDATE EST_NF_ENT
		   SET STS_NF = 0
		 WHERE CD_EMP = 1
		   AND CD_FILIAL = @CD_FILIAL
	   	   AND CD_NF = @CD_NF
		   AND STS_NF = 1;

		DELETE I
		  FROM EST_NF_NFE_INU I
				INNER JOIN EST_NF_ENT_EST_NF_NFE_INU L ON I.CD_EMP = L.CD_EMP
													  AND I.CD_FILIAL = L.CD_FILIAL
													  AND I.CD_INU = L.CD_INU
		 WHERE I.CD_EMP = 1
		   AND I.CD_FILIAL = @CD_FILIAL
		   AND L.CD_NF = @CD_NF;

		SET @CD_INU = (SELECT I.CD_INU
						 FROM EST_NF_NFE_INU I
							  INNER JOIN EST_NF_ENT_EST_NF_NFE_INU L ON I.CD_EMP = L.CD_EMP
																	AND I.CD_FILIAL = L.CD_FILIAL
																	AND I.CD_INU = L.CD_INU
						 WHERE I.CD_EMP = 1
						   AND I.CD_FILIAL = @CD_FILIAL
						   AND L.CD_NF = @CD_NF  );

		EXEC P_NFE_REINSERIR_PENDENCIA_EMISSAO 'E',1 ,@CD_FILIAL ,0 ,@CD_NF;

		DELETE
		  FROM EST_NF_ENT_EST_NF_NFE_INU
		 WHERE CD_INU = @CD_INU;
	END

	DELETE 
	  FROM EST_NFE_LOTE_EST_NF_NFE_INU
	 WHERE CD_INU = @CD_INU;

	DELETE
	  FROM EST_NF_NFE_INU_PEND
 	 WHERE CD_INU = @CD_INU;

	DELETE
	  FROM EST_NFE_LOTE_INU_ERR
	 WHERE CD_INU = @CD_INU;

	DELETE
	  FROM EST_NF_NFE_INU
	 WHERE CD_INU = @CD_INU;
END
