IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[P_ESTORNA_MOV_CREDITO_ICMS_ST_PIS_COFINS]') 
					AND type in (N'P', N'PC'))
	BEGIN
		DROP PROCEDURE [DBO].[P_ESTORNA_MOV_CREDITO_ICMS_ST_PIS_COFINS]
	END
GO

CREATE PROCEDURE [dbo].[P_ESTORNA_MOV_CREDITO_ICMS_ST_PIS_COFINS]
    @PROT_ICMS_ST INT,
	@CD_EMP INT,
	@CD_FILIAL INT,
	@TIPO_DOC INT,
	@CD_DOC INT,
	@QT_IT INT,
	@CD_PROD INT
AS
BEGIN
    DECLARE @CD_NF INT;


	IF (SELECT STATUS FROM EST_NF_ENT_ENTRADA_ICMS_ST_MOV WHERE PROT_ICMS_ST = @PROT_ICMS_ST) = 1
	BEGIN
	
		IF NOT EXISTS (SELECT 1 
						FROM EST_NF_ENT_ENTRADA_ICMS_ST_MOV 
						WHERE PROT_ICMS_ST_SAIDA = @PROT_ICMS_ST 
						AND STATUS = 3)
		BEGIN
	

			INSERT INTO EST_NF_ENT_ENTRADA_ICMS_ST_MOV (CD_EMP
															,CD_FILIAL
															,CD_NF_ENT_CRED
															,TIPO_DOC
															,CD_DOC
															,CD_PROD
															,QT_IT
															,VLR_ICMS_ST_DARE
															,VLR_ICMS_EFETIVO
															,VLR_ICMS_SUBS
															,VLR_ICMS_RET
															,VLR_FECOP
															,VLR_FECOP_RET
															,VLR_FECOP_ST
															,STATUS
															,PROT_ICMS_ST_SAIDA
															,DT_CAD)
				SELECT CD_EMP
						,CD_FILIAL
						,CD_NF_ENT_CRED
						,@TIPO_DOC
						,@CD_DOC
						,CD_PROD
						,@QT_IT * (-1)
						,VLR_ICMS_ST_DARE
						,VLR_ICMS_EFETIVO
						,VLR_ICMS_SUBS
						,VLR_ICMS_RET
						,VLR_FECOP
						,VLR_FECOP_RET
						,VLR_FECOP_ST
						,3
						,PROT_ICMS_ST as PROT_ICMS_ST_SAIDA
						,getdate()
				FROM EST_NF_ENT_ENTRADA_ICMS_ST_MOV
				WHERE PROT_ICMS_ST = @PROT_ICMS_ST;


				SELECT @CD_NF = CD_NF_ENT_CRED
				FROM EST_NF_ENT_ENTRADA_ICMS_ST_MOV 
				WHERE PROT_ICMS_ST = @PROT_ICMS_ST;


				UPDATE EST_NF_ENT_CREDITO_ICMS_ST_PIS_COFINS 
					SET SALDO_ZERADO = 0
				WHERE CD_NF = @CD_NF 
					AND CD_FILIAL = @CD_FILIAL 
					AND CD_EMP = @CD_EMP;
			END
			ELSE
			BEGIN
				RAISERROR ('Já existe um estorno para este protocolo!', 16, 1);
			END
		END
		ELSE
		BEGIN
			RAISERROR ('O protocolo não está confirmado!', 16, 1);
		END

END


GO


