/****** Object:  StoredProcedure [dbo].[P_EST_NF_ENT_CORRIGE_CFOP]    Script Date: 02/11/2014 18:34:05 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[P_EST_NF_ENT_CORRIGE_CFOP]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[P_EST_NF_ENT_CORRIGE_CFOP]
GO
GO 
--EXEC P_EST_NF_ENT_CORRIGE_CFOP 1, 999, '2015-08-01', '2015-08-31',1
CREATE PROCEDURE P_EST_NF_ENT_CORRIGE_CFOP (@CD_EMP INT, 
											@CD_FILIAL INT, 
											@DT_INI DATETIME, 
											@DT_FIM DATETIME, 
											@FLAG_ANALISA INT)
WITH ENCRYPTION
AS
BEGIN
SET NOCOUNT ON
CREATE TABLE #RSNOTADIVERGENTE(CD_EMP INT,
							   CD_FILIAL INT,
							   CD_NF INT,
							   CD_PROD INT,
							   NR_NF INT,
							   DS_MOV_OP VARCHAR(150),
							   APLICATIVO VARCHAR(30),
							   CST_NOTA VARCHAR (3),
							   CD_NT_OP_NOTA INT,
							   CFOP_NOTA VARCHAR (10),
							   CD_NT_OP_CORRECAO INT,
							   CFOP_CORRECAO VARCHAR(10))

INSERT INTO #RSNOTADIVERGENTE
SELECT
	 I.CD_EMP,
	 I.CD_FILIAL,
	 I.CD_NF,
	 I.CD_PROD,
	 E.NR_NF,
	 M.DS_MOV_OP_USUAL,
	 E.APLICATIVO,
	 EST_TRIB.CD_TRIB_FC AS CST_NOTA,
	 I.CD_NT_OP,
	 GLB_NT_OP.CD_NT_OP_FC AS CFOP_NOTA,
	 A.*
FROM
	EST_NF_ENT E INNER JOIN EST_NF_ENT_IT I ON
	E.CD_EMP = I.CD_EMP AND
	E.CD_FILIAL = I.CD_FILIAL AND
	E.CD_NF = I.CD_NF AND
	E.DT_ENT = I.DT_ENT
	INNER JOIN GLB_MOV_OP M ON
	E.CD_NT_MOV = M.CD_MOV_OP
	INNER JOIN EST_TRIB ON
	I.CD_TRIB = EST_TRIB.CD_TRIB
	INNER JOIN GLB_NT_OP ON
	I.CD_NT_OP = GLB_NT_OP.CD_NT_OP
	OUTER APPLY UFD_MONTAR_CFOP(I.CD_EMP,I.CD_FILIAL,E.CD_NT_MOV,I.CD_TRIB,E.CD_FORN,0,0,0)  A
WHERE
	I.CD_EMP=@CD_EMP
	AND I.CD_FILIAL=CASE WHEN @CD_FILIAL=0 THEN I.CD_FILIAL ELSE @CD_FILIAL END
	AND I.DT_ENT BETWEEN @DT_INI AND @DT_FIM
	AND I.CD_NT_OP <> A.CD_NT_OP 

IF @FLAG_ANALISA=0 
BEGIN
	SELECT
		*
	FROM
		#RSNOTADIVERGENTE
END

IF @FLAG_ANALISA=1
BEGIN
	UPDATE
		I
	SET 
		CD_NT_OP = CD_NT_OP_CORRECAO
	FROM
		EST_NF_ENT_IT I INNER JOIN #RSNOTADIVERGENTE D ON
		I.CD_EMP = D.CD_EMP AND
		I.CD_FILIAL = D.CD_FILIAL AND
		I.CD_NF = D.CD_NF AND
		I.CD_PROD = D.CD_PROD 
	WHERE
		NOT CD_NT_OP_CORRECAO IS NULL
END

	DROP TABLE #RSNOTADIVERGENTE
END