/****** Object:  StoredProcedure [dbo].[P_EST_NF_SAI_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_SAI_CORRIGE_CFOP]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[P_EST_NF_SAI_CORRIGE_CFOP]
GO
GO 
--EXEC P_EST_NF_SAI_CORRIGE_CFOP 1, 999, '2015-08-31', '2015-08-31',1
CREATE PROCEDURE P_EST_NF_SAI_CORRIGE_CFOP (@CD_EMP INT, 
											@CD_FILIAL INT, 
											@DT_INI DATETIME, 
											@DT_FIM DATETIME, 
											@FLAG_ANALISA INT)
AS
BEGIN
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,
	 S.NF_NF,
	 M.DS_MOV_OP_USUAL,
	 S.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_SAI S INNER JOIN EST_NF_SAI_IT I ON
	S.CD_EMP = I.CD_EMP AND
	S.CD_FILIAL = I.CD_FILIAL AND
	S.CD_NF = I.CD_NF AND
	S.DT_EMI_NF = I.DT_EMI_NF
	INNER JOIN GLB_MOV_OP M ON
	S.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,S.CD_NT_MOV,I.CD_TRIB,S.CD_CLI,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_EMI_NF 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_SAI_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