IF EXISTS (SELECT
						 *
					 FROM
						 sys.objects
					 WHERE
						object_id = OBJECT_ID('[dbo].[P_EST_NF_ENT_DANFE_PROVISORIO_BLOQUEIO_PENDENTE]') AND
						type IN ( 'P', 'PC' ))
	DROP PROCEDURE [dbo].[P_EST_NF_ENT_DANFE_PROVISORIO_BLOQUEIO_PENDENTE]
GO
-- P_EST_NF_ENT_DANFE_PROVISORIO_BLOQUEIO_PENDENTE 11,213835
/*
=======================================================================================
'Job.................:  
'Função..............: 
'Objetivo............: Alterar codigo do produto 
'Tabelas.............: 
'Dt Modificação......: 20/04/2021
'Modificação.........: Tag #A001 Padronizar para usuario 1
'=======================================================================================
Tag #A001 - Alteração do codigo  
Tag #I001 - Inclusão de novo codigo 
*/
CREATE PROCEDURE P_EST_NF_ENT_DANFE_PROVISORIO_BLOQUEIO_PENDENTE (@CD_FILIAL    INT = 0, @CD_CTR_DANFE INT=0)
 
AS
		SET NOCOUNT ON;

		SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;
		DECLARE @FLAG_DESATIVAR_DIVERG_COND_PGTO_PEDIDO INT,@FLAG_DESATIVAR_DIVERG_VALOR_PGTO_PEDIDO TINYINT; 
		DECLARE @VLR_DIV MONEY =ISNULL((SELECT replace(VALOR, ',', '.' ) FROM PRC_EMP_CONFIG
											 WHERE
												CD_CHAVE = 'VLR_MAX_DIVERGENCIA_DANFE_X_PEDIDO'), 0.02);

		SET @FLAG_DESATIVAR_DIVERG_COND_PGTO_PEDIDO =ISNULL((SELECT VALOR FROM PRC_EMP_CONFIG WHERE CD_CHAVE = 'FLAG_DESATIVAR_DIVERG_COND_PGTO_PEDIDO'),0);
		SET @FLAG_DESATIVAR_DIVERG_VALOR_PGTO_PEDIDO =ISNULL((SELECT VALOR FROM PRC_EMP_CONFIG WHERE CD_CHAVE = 'FLAG_DESATIVAR_DIVERG_VALOR_PGTO_PEDIDO'),0);

		DECLARE @DT_CORTE DATETIME = DATEADD(month, -2, GETDATE());

		DECLARE @ConsideraDanfeEmpresa SMALLINT;
		set @ConsideraDanfeEmpresa = ISNULL((SELECT VALOR FROM 
									 PRC_EMP_CONFIG 
									 WHERE CD_CHAVE= 'CONTROLE_SALDO_VINCULO_NOTA_COM_PEDIDO'),0)
/*********************************************************************************************************************/

		print 'Corrigindo percentual de desconto do danfe - ' + convert (varchar,getdate(),108)
		--Corrigindo percentual de desconto do danfe
		UPDATE
			EST_NF_ENT_DANFE_PROVISORIO_ITENS
		SET 
			PERC_PROD_DESC=((VLR_PROD_DESC/QTDE_PROD)/VLR_PROD_UNIT)*100.00
		FROM
			EST_NF_ENT_DANFE_PROVISORIO_ITENS 
			INNER JOIN EST_NF_ENT_DANFE_PROVISORIO_PENDENTE ON
			EST_NF_ENT_DANFE_PROVISORIO_ITENS.CD_CTR = EST_NF_ENT_DANFE_PROVISORIO_PENDENTE.CD_CTR 
				INNER JOIN EST_NF_ENT_DANFE_PROVISORIO ON
			EST_NF_ENT_DANFE_PROVISORIO_ITENS.CD_CTR = EST_NF_ENT_DANFE_PROVISORIO.CD_CTR
		WHERE
				EST_NF_ENT_DANFE_PROVISORIO_ITENS.VLR_PROD_DESC > 0 
			AND EST_NF_ENT_DANFE_PROVISORIO_ITENS.PERC_PROD_DESC = 0
			AND EST_NF_ENT_DANFE_PROVISORIO_ITENS.VLR_PROD_UNIT > 0
			and EST_NF_ENT_DANFE_PROVISORIO.CD_EMP = 1 
			AND EST_NF_ENT_DANFE_PROVISORIO.CD_FILIAL=@CD_FILIAL 
		--fim
		
		--Corrigindo xPed dos itens e do Cabecalho quando possuir zeros a esquerda
		UPDATE
			EST_NF_ENT_DANFE_PROVISORIO_ITENS
		SET
			EST_NF_ENT_DANFE_PROVISORIO_ITENS.XPED_IT= SUBSTRING(EST_NF_ENT_DANFE_PROVISORIO_ITENS.XPED_IT, PATINDEX('%[^0]%', EST_NF_ENT_DANFE_PROVISORIO_ITENS.XPED_IT+'.'), LEN(EST_NF_ENT_DANFE_PROVISORIO_ITENS.XPED_IT))
		FROM
			EST_NF_ENT_DANFE_PROVISORIO_ITENS 
			INNER JOIN EST_NF_ENT_DANFE_PROVISORIO ON
			EST_NF_ENT_DANFE_PROVISORIO_ITENS.CD_CTR = EST_NF_ENT_DANFE_PROVISORIO.CD_CTR
			INNER JOIN EST_NF_ENT_DANFE_PROVISORIO_PENDENTE ON
			EST_NF_ENT_DANFE_PROVISORIO_ITENS.CD_CTR = EST_NF_ENT_DANFE_PROVISORIO_PENDENTE.CD_CTR
		WHERE
			EST_NF_ENT_DANFE_PROVISORIO_ITENS.XPED_IT<>SUBSTRING(EST_NF_ENT_DANFE_PROVISORIO_ITENS.XPED_IT, PATINDEX('%[^0]%', EST_NF_ENT_DANFE_PROVISORIO_ITENS.XPED_IT+'.'), LEN(EST_NF_ENT_DANFE_PROVISORIO_ITENS.XPED_IT))
			and EST_NF_ENT_DANFE_PROVISORIO.CD_EMP = 1 
			AND EST_NF_ENT_DANFE_PROVISORIO.CD_FILIAL=@CD_FILIAL 

		UPDATE
			EST_NF_ENT_DANFE_PROVISORIO
		SET
			EST_NF_ENT_DANFE_PROVISORIO.CD_PED_FORN= SUBSTRING(EST_NF_ENT_DANFE_PROVISORIO.CD_PED_FORN, PATINDEX('%[^0]%', EST_NF_ENT_DANFE_PROVISORIO.CD_PED_FORN+'.'), LEN(EST_NF_ENT_DANFE_PROVISORIO.CD_PED_FORN))
		FROM
			EST_NF_ENT_DANFE_PROVISORIO INNER JOIN EST_NF_ENT_DANFE_PROVISORIO_PENDENTE ON
			EST_NF_ENT_DANFE_PROVISORIO.CD_CTR = EST_NF_ENT_DANFE_PROVISORIO_PENDENTE.CD_CTR
		WHERE
			EST_NF_ENT_DANFE_PROVISORIO.CD_PED_FORN<>SUBSTRING(EST_NF_ENT_DANFE_PROVISORIO.CD_PED_FORN, PATINDEX('%[^0]%', EST_NF_ENT_DANFE_PROVISORIO.CD_PED_FORN+'.'), LEN(EST_NF_ENT_DANFE_PROVISORIO.CD_PED_FORN))		
			and EST_NF_ENT_DANFE_PROVISORIO.CD_EMP = 1 
			AND EST_NF_ENT_DANFE_PROVISORIO.CD_FILIAL=@CD_FILIAL 
		--Fim
		
		print 'Retirando zeros a esquerda do pedido fornecedor - ' + convert (varchar,getdate(),108)
		--Retirando zeros a esquerda do pedido fornecedor
		UPDATE
			EST_PED_CP
		SET   
			EST_PED_CP.CD_PED_FORN=SUBSTRING(CD_PED_FORN, PATINDEX('%[^0]%', CD_PED_FORN+'.'), LEN(CD_PED_FORN))
		FROM
			EST_PED_CP INNER JOIN EST_PED_CP_PENDENCIA ON
			EST_PED_CP.CD_EMP = EST_PED_CP_PENDENCIA.CD_EMP AND 
			EST_PED_CP.CD_FILIAL = EST_PED_CP_PENDENCIA.CD_FILIAL AND
			EST_PED_CP.CD_PED = EST_PED_CP_PENDENCIA.CD_PED
		WHERE
			CD_PED_FORN<>SUBSTRING(CD_PED_FORN, PATINDEX('%[^0]%', CD_PED_FORN+'.'), LEN(CD_PED_FORN))
			and EST_PED_CP.CD_EMP = 1 
			AND EST_PED_CP.CD_FILIAL=@CD_FILIAL 

		print 'Atualizando xped do Cabeçalho com base no xped dos itens (quando houver somente 1 xped nos itens) - ' + convert (varchar,getdate(),108)
		UPDATE
			EST_NF_ENT_DANFE_PROVISORIO
		SET
			EST_NF_ENT_DANFE_PROVISORIO.CD_PED_FORN= XPED_IT
		FROM
			EST_NF_ENT_DANFE_PROVISORIO 
			JOIN (
				SELECT EST_NF_ENT_DANFE_PROVISORIO_ITENS.CD_CTR, CD_EMP, MIN(XPED_IT) AS XPED_IT
				FROM EST_NF_ENT_DANFE_PROVISORIO_ITENS
				INNER JOIN EST_NF_ENT_DANFE_PROVISORIO_PENDENTE ON
				EST_NF_ENT_DANFE_PROVISORIO_ITENS.CD_CTR = EST_NF_ENT_DANFE_PROVISORIO_PENDENTE.CD_CTR 
				GROUP BY EST_NF_ENT_DANFE_PROVISORIO_ITENS.CD_CTR, CD_EMP
				HAVING COUNT(DISTINCT XPED_IT) = 1
			) B ON B.CD_CTR = EST_NF_ENT_DANFE_PROVISORIO.CD_CTR AND B.CD_EMP = EST_NF_ENT_DANFE_PROVISORIO.CD_EMP
			INNER JOIN EST_NF_ENT_DANFE_PROVISORIO_PENDENTE ON
			EST_NF_ENT_DANFE_PROVISORIO.CD_CTR = EST_NF_ENT_DANFE_PROVISORIO_PENDENTE.CD_CTR
		WHERE
			DT_EMIS_NF > @DT_CORTE AND
			CD_PED_FORN <> XPED_IT AND
			LTRIM(RTRIM(ISNULL(EST_NF_ENT_DANFE_PROVISORIO.CD_PED_FORN,''))) = ''
			AND EST_NF_ENT_DANFE_PROVISORIO.CD_FILIAL=@CD_FILIAL 
		


/*********************************************************************************************************************/
		print 'Inserindo est_nf_ent_danfe_provisorio_est_ped_cp - ' + convert (varchar,getdate(),108)	
		/*
		INSERT INTO EST_NF_ENT_DANFE_PROVISORIO_EST_PED_CP
								(CD_CTR,
								 CD_EMP,
								 CD_FILIAL,
								 CD_PED,
								 CD_USU,
								 DT_CAD)		
		SELECT
			D.CD_CTR
			,D.CD_EMP
			,D.CD_FILIAL
			,F.CD_PED
			,1         CD_USU
			,GETDATE() DT_CAD
		FROM
			EST_NF_ENT_DANFE_PROVISORIO d with (nolock)
			INNER JOIN EST_NF_ENT_DANFE_PROVISORIO_EST_NF_ENT E with (nolock) ON
			D.CD_CTR = E.CD_CTR
			INNER JOIN (SELECT
										F.CD_EMP
										,F.CD_FILIAL
										,F.CD_FORN
										,F.CD_PED_FORN
										,MAX(f.CD_PED) CD_PED
									FROM
										EST_PED_CP F with (nolock)
										join est_ped_cp_it i with (nolock) on 
											f.cd_emp = i.cd_emp and
											f.cd_filial = i.cd_filial and
											f.cd_ped = i.cd_ped
									WHERE
									 LEN(F.CD_PED_FORN)  > 2  AND
									 F.STS_PED IN( 0, 1 )
									GROUP  BY
									 F.CD_EMP
									 ,F.CD_FILIAL
									 ,F.CD_FORN
									 ,F.CD_PED_FORN) F ON
				D.CD_EMP = F.CD_EMP AND
				D.CD_FILIAL = F.CD_FILIAL AND
				D.CD_FORN = F.CD_FORN AND
				D.CD_PED_FORN = CONVERT (VARCHAR ,F.CD_PED_FORN)
			LEFT JOIN EST_NF_ENT_DANFE_PROVISORIO_EST_PED_CP C with (nolock) ON
				D.CD_CTR = C.CD_CTR
		WHERE
			D.DT_EMIS_NF > @DT_CORTE AND
			c.CD_EMP IS NULL AND
			D.CD_EMP     = 1 AND
			D.CD_FILIAL=@CD_FILIAL AND
			C.CD_EMP IS NULL;*/
	
	Declare @sqlCmd as varchar(8000)='';

	set @sqlCmd  = 'INSERT INTO EST_NF_ENT_DANFE_PROVISORIO_EST_PED_CP
								(CD_CTR,
								 CD_EMP,
								 CD_FILIAL,
								 CD_PED,
								 CD_USU,
								 DT_CAD)	
	SELECT
			D.CD_CTR
			,D.CD_EMP
			,D.CD_FILIAL
			,F.CD_PED
			,1         CD_USU
			,GETDATE() DT_CAD
		FROM
			EST_NF_ENT_DANFE_PROVISORIO d with (nolock)
			INNER JOIN EST_NF_ENT_DANFE_PROVISORIO_EST_NF_ENT E with (nolock) ON
			D.CD_CTR = E.CD_CTR
			INNER JOIN (SELECT
										F.CD_EMP
										,F.CD_FILIAL
										,F.CD_FORN
										,F.CD_PED_FORN
										,MIN(f.CD_PED) CD_PED
									FROM
										EST_PED_CP F with (nolock)
										join est_ped_cp_it i with (nolock) on 
											f.cd_emp = i.cd_emp and
											f.cd_filial = i.cd_filial and
											f.cd_ped = i.cd_ped
										LEFT JOIN EST_PED_CP_PED_CP_FORN_VINCULADO V ON V.CD_EMP=F.CD_EMP AND V.CD_FILIAL=F.CD_FILIAL AND V.CD_PED_VINC=F.CD_PED
									WHERE
									 LEN(F.CD_PED_FORN)  > 2  AND
									 F.STS_PED IN( 0, 1 )
									 AND V.CD_PED_VINC IS NULL
									GROUP  BY
									 F.CD_EMP
									 ,F.CD_FILIAL
									 ,F.CD_FORN
									 ,F.CD_PED_FORN
									 HAVING (SUM(DBO.[UFD_EST_PED_CP_IT_SLD_DANFE] (F.CD_EMP,F.CD_FILIAL,F.CD_PED,I.CD_PROD,1,0)) >= ' + convert(varchar,@ConsideraDanfeEmpresa) + ')
									 ) F ON
				D.CD_EMP = F.CD_EMP AND
				D.CD_FILIAL = F.CD_FILIAL AND
				D.CD_FORN = F.CD_FORN AND
				D.CD_PED_FORN = CONVERT (VARCHAR ,F.CD_PED_FORN)
			LEFT JOIN EST_NF_ENT_DANFE_PROVISORIO_EST_PED_CP C with (nolock) ON
				D.CD_CTR = C.CD_CTR
		WHERE
			D.DT_EMIS_NF > ''' + convert(varchar, @DT_CORTE,112) + ''' AND
			c.CD_EMP IS NULL AND
			D.CD_EMP     = 1 AND
			D.CD_FILIAL= ' + convert(varchar, @CD_FILIAL) + ' AND
			C.CD_EMP IS NULL;'

	exec (@sqlCmd);

/*********************************************************************************************************************/
		--Deletando pendencia de danfe ja bloqueado
/*********************************************************************************************************************/
/*********************************************************************************************************************/
	DELETE
		B
	FROM
		EST_NF_ENT_DANFE_PROVISORIO_BLOQUEIO P 
		INNER JOIN  EST_NF_ENT_DANFE_PROVISORIO_BLOQUEIO_PENDENTE B ON
		P.CD_CTR = B.CD_CTR AND 
		P.TIPO_BLQ = B.TIPO_BLQ;

	IF EXISTS( SELECT  D.CD_EMP
				FROM
				EST_NF_ENT_DANFE_PROVISORIO_EST_PED_CP D
				INNER JOIN EST_NF_ENT_DANFE_PROVISORIO_EST_NF_ENT DE ON
				D.CD_CTR = DE.CD_CTR
				AND D.CD_FILIAL <> DE.CD_FILIAL 
				WHERE 
				DE.CD_EMP = 1 
				AND DE.CD_FILIAL = @CD_FILIAL 
				AND D.CD_EMP=1)
		BEGIN 

				DELETE FROM D
				FROM
					EST_NF_ENT_DANFE_PROVISORIO_EST_PED_CP D
					INNER JOIN EST_NF_ENT_DANFE_PROVISORIO_EST_NF_ENT DE ON
						D.CD_CTR = DE.CD_CTR
					AND D.CD_FILIAL <> DE.CD_FILIAL 
				 WHERE 
					DE.CD_EMP = 1 
					AND DE.CD_FILIAL = @CD_FILIAL 
		END

/*********************************************************************************************************************/
    PRINT 'Vinculo da nota fiscal com o  pedido de compras pelo danfe - Time ' + convert(varchar(20),getdate(),108);
    
   
		SET @sqlCmd = 'INSERT INTO EST_NF_ENT_PED_CP(CD_EMP, CD_FILIAL, CD_PED, CD_NF, DT_CAD) 
		SELECT DISTINCT
					D.CD_EMP
				, D.CD_FILIAL
				, D.CD_PED
				, DE.CD_NF
				, GETDATE()
		FROM
			EST_NF_ENT_DANFE_PROVISORIO_EST_PED_CP D
			INNER JOIN EST_NF_ENT_DANFE_PROVISORIO_EST_NF_ENT DE ON D.CD_CTR = DE.CD_CTR
			INNER JOIN EST_NF_ENT ON		DE.CD_EMP	 = EST_NF_ENT.CD_EMP
										AND DE.CD_FILIAL = EST_NF_ENT.CD_FILIAL
										AND DE.CD_NF	 = EST_NF_ENT.CD_NF
			LEFT OUTER JOIN EST_NF_ENT_PED_CP E ON D.CD_EMP = E.CD_EMP
													AND D.CD_FILIAL = E.CD_FILIAL
													AND de.CD_NF = E.CD_NF
		WHERE  E.CD_NF IS NULL
				AND EST_NF_ENT.CD_EMP = 1
				AND EST_NF_ENT.CD_FILIAL = ' + convert(varchar, @CD_FILIAL) + ' 
				AND EST_NF_ENT.DT_ENT > ''' +  convert(varchar, @DT_CORTE,112) + ''''
			 

	exec (@sqlCmd)


/*********************************************************************************************************************/
		--Procedimentos auxiliares
/*********************************************************************************************************************/
/*********************************************************************************************************************/
		--Libera a pre entrada do que ja foi liberado
		WHILE EXISTS(SELECT  A.CD_CTR
							FROM
								EST_NF_ENT_DANFE_PROVISORIO_LIBERACAO_TIPO_BLQ A
								INNER JOIN EST_NF_ENT_DANFE_PROVISORIO_EST_NF_ENT_PRE_ENTRADA B ON
									A.CD_CTR = B.CD_CTR
								LEFT JOIN EST_NF_ENT_PRE_ENTRADA_LIB E ON
									B.CD_EMP = E.CD_EMP AND
									B.CD_CTR_PRE_ENTRADA = E.CD_CTR_PRE_ENTRADA
							WHERE
								E.CD_EMP IS NULL AND
								A.TIPO_BLQ IN( 7, 8, 9 )
						)
		BEGIN
			INSERT INTO EST_NF_ENT_PRE_ENTRADA_LIB
			SELECT TOP 1
				B.CD_EMP
				,B.CD_CTR_PRE_ENTRADA
				,MIN(CD_USU_LIB) CD_USU
				,GETDATE()       DT_CAD
			FROM
				EST_NF_ENT_DANFE_PROVISORIO_LIBERACAO_TIPO_BLQ A
				INNER JOIN EST_NF_ENT_DANFE_PROVISORIO_EST_NF_ENT_PRE_ENTRADA B ON
					A.CD_CTR = B.CD_CTR
				LEFT JOIN EST_NF_ENT_PRE_ENTRADA_LIB E ON
					B.CD_EMP = E.CD_EMP AND
					B.CD_CTR_PRE_ENTRADA = E.CD_CTR_PRE_ENTRADA
			WHERE
				E.CD_EMP IS NULL AND
				A.TIPO_BLQ IN( 7, 8, 9 )
			GROUP  BY
				B.CD_EMP
				,B.CD_CTR_PRE_ENTRADA
		END

		SET TRANSACTION ISOLATION LEVEL READ COMMITTED;
		
		PRINT 'Danfe liberado pelo cadastro do fornecedor - Time ' + convert(varchar(20),getdate(),108);
		
 --Tag #A001   
		INSERT INTO EST_NF_ENT_DANFE_PROVISORIO_LIBERACAO(CD_CTR, CD_USU, DT_CAD, TIPO_BLQ, 
																CD_PED_COMPRA, DT_LIBERACAO, CD_USU_LIB,OBS_LIB)
		SELECT
			D.CD_CTR
			,1
			,CONVERT(CHAR(10),GETDATE(),112)
			,3
			,0
			,GETDATE()
			,1 							 
			,'CADASTRO DO FORNECEDOR CONFIGURADO PARA LIBERAR ENTRADA SEM VINCULO COM O PEDIDO DE COMPRAS'
		FROM
			EST_NF_ENT_DANFE_PROVISORIO D
			INNER JOIN EST_NF_ENT_DANFE_PROVISORIO_PENDENTE Y WITH (NOLOCK)  ON
				D.CD_CTR = Y.CD_CTR
			INNER JOIN PG_FORN P ON
				D.CD_EMP = P.CD_EMP AND
				D.CD_FORN = P.CD_FORN
			LEFT OUTER JOIN EST_NF_ENT_DANFE_PROVISORIO_LIBERACAO LI ON
				D.CD_CTR = LI.CD_CTR
		WHERE
			P.FLAG_ENTRAR_NF_SEM_VINC_PEDIDO = 1
			AND LI.CD_CTR IS NULL
			AND D.CD_FILIAL = @CD_FILIAL
			AND D.DT_EMIS_NF > @DT_CORTE
			AND D.CD_EMP = 1

			 

		--Fim
		SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;

		PRINT 'Remove vinculos pedidos com fornecedores invalidos '
					+ CONVERT(VARCHAR, GETDATE(), 108);

		DELETE FROM EP
		FROM   EST_NF_ENT_PED_CP EP
					 INNER JOIN EST_NF_ENT E ON
						 EP.CD_EMP = E.CD_EMP AND
						 EP.CD_FILIAL = E.CD_FILIAL AND
						 EP.CD_NF = E.CD_NF
					 INNER JOIN EST_PED_CP P ON
						 EP.CD_EMP = P.CD_EMP AND
						 EP.CD_FILIAL = P.CD_FILIAL AND
						 EP.CD_PED = P.CD_PED
		WHERE  E.CD_FORN   <> P.CD_FORN AND
					 E.CD_EMP    = 1 AND
					 E.CD_FILIAL = @CD_FILIAL AND
					 E.DT_ENT    > @DT_CORTE

		--Atualiza sts ped
		PRINT 'Atualiza o status do pedido com nota de entrada '
					+ CONVERT(VARCHAR, GETDATE(), 108);

		CREATE TABLE #TMP_STS_PED
			(
				 CD_EMP    INT,
				 CD_FILIAL INT,
				 CD_PED    INT,
				 QT_PEDIDO MONEY,
				 QT_SALDO  MONEY,
				 POSSUI_NF INT,
				 STS_PED   INT
			)

		SET @sqlCmd = 'INSERT INTO #TMP_STS_PED
		SELECT
			P.CD_EMP
			,P.CD_FILIAL
			,P.CD_PED
			,SUM(P.QT_SALDO)          QT_PEDIDO
			,SUM(CASE WHEN P.QT_SALDO - ISNULL(N.QT_ENTROU, 0) < 0 THEN 0
					 ELSE P.QT_SALDO - ISNULL(N.QT_ENTROU, 0)
					 END)                 QT_SALDO
			,SUM(ISNULL(N.CD_EMP, 0)) POSSUI_NF
			,NULL                     STS_PED
		FROM
			(SELECT
				 I.CD_EMP
				 ,I.CD_FILIAL
				 ,I.CD_PED
				 ,I.CD_PROD
				 ,ISNULL(SUM(I.QT_IT * I.QT_EMB), 0) - ISNULL(SUM(C.QT_PROD), 0) QT_SALDO
			 FROM
				 EST_PED_CP P
				 INNER JOIN EST_PED_CP_IT I ON
					 P.CD_EMP = I.CD_EMP AND
					 P.CD_FILIAL = I.CD_FILIAL AND
					 P.CD_PED = I.CD_PED
				 LEFT OUTER JOIN EST_PED_CP_IT_CANCEL_SLD C ON
					 I.CD_EMP = C.CD_EMP AND
					 I.CD_FILIAL = C.CD_FILIAL AND
					 I.CD_PED = C.CD_PED AND
					 I.CD_PROD = C.CD_PROD
			 WHERE
				P.CD_EMP    = 1 AND
				P.CD_FILIAL = ' + convert(varchar,  @CD_FILIAL) + ' AND P.DT_EMI > ''' + convert(varchar,@DT_CORTE,112) + ''' AND  P.STS_PED   = 3
			 GROUP  BY
				I.CD_EMP
				,I.CD_FILIAL
				,I.CD_PED
				,I.CD_PROD) P
			LEFT JOIN (SELECT I.CD_EMP
									 ,I.CD_FILIAL
									 ,EST_NF_ENT_PED_CP.CD_PED
									 ,I.CD_PROD
									 ,ISNULL(SUM(I.QT_IT), 0) QT_ENTROU
								 FROM
									 EST_NF_ENT_PED_CP
									 INNER JOIN EST_NF_ENT_IT I ON
										 EST_NF_ENT_PED_CP.CD_EMP = I.CD_EMP AND
										 EST_NF_ENT_PED_CP.CD_FILIAL = I.CD_FILIAL AND
										 EST_NF_ENT_PED_CP.CD_NF = I.CD_NF
								 WHERE
									i.CD_EMP    = 1 AND
									i.CD_FILIAL = ' + convert(varchar,  @CD_FILIAL) + ' AND i.DT_ENT > ''' + convert(varchar,@DT_CORTE,112) + '''   
								 GROUP  BY
									I.CD_EMP
									,I.CD_FILIAL
									,EST_NF_ENT_PED_CP.CD_PED
									,I.CD_PROD) N ON
				P.CD_EMP = N.CD_EMP AND
				P.CD_FILIAL = N.CD_FILIAL AND
				P.CD_PROD = N.CD_PROD AND
				P.CD_PED = N.CD_PED
		WHERE
			P.CD_EMP = 1
		GROUP  BY
			P.CD_EMP
			,P.CD_FILIAL
			,P.CD_PED;'

		EXEC (@sqlCmd); 

		CREATE UNIQUE CLUSTERED INDEX IX_#TMP_STS_PED
			ON #TMP_STS_PED (CD_PED, CD_FILIAL, CD_EMP);

		PRINT 'Atualiza o status do pedido '
					+ CONVERT(VARCHAR, GETDATE(), 108);

		UPDATE #TMP_STS_PED
		SET    STS_PED = CASE WHEN ( QT_PEDIDO ) = ( QT_SALDO ) AND
													( QT_PEDIDO ) > 0 THEN --Se for igual ao pedido
										 0
										 WHEN ( QT_SALDO ) <> 0 THEN --Saldo maior que zero
										 1
										 WHEN ( QT_SALDO ) = 0 THEN --Saldo zerados
											 CASE WHEN POSSUI_NF > 0 THEN 3
											 ELSE 2
											 END
										 ELSE NULL
										 END;

		DELETE FROM #TMP_STS_PED
		WHERE  STS_PED IS NULL;

		PRINT 'Remove pedidos sem saldo.. vinculados com danfe pendente de entrada '
					+ CONVERT(VARCHAR, GETDATE(), 108);

		--Remove pedidos sem saldo.. vinculados com danfe pendente de entrada..
		DELETE FROM A
		FROM   EST_NF_ENT_DANFE_PROVISORIO_EST_PED_CP A
					 INNER JOIN EST_NF_ENT_DANFE_PROVISORIO_PENDENTE B ON
						 A.CD_CTR = B.CD_CTR
					 INNER JOIN #TMP_STS_PED P ON
						 A.CD_EMP = P.CD_EMP AND
						 A.CD_FILIAL = P.CD_FILIAL AND
						 A.CD_PED = P.CD_PED
		WHERE  P.STS_PED   = 2 AND
					 A.CD_EMP    = 1 AND
					 A.CD_FILIAL = @CD_FILIAL;

		PRINT 'Atualização dos status de pedido '
					+ CONVERT(VARCHAR, GETDATE(), 108);

		UPDATE P
		SET    STS_PED = A.STS_PED
		FROM   #TMP_STS_PED A
					 INNER JOIN EST_PED_CP P ON
						 A.CD_EMP = P.CD_EMP AND
						 A.CD_FILIAL = P.CD_FILIAL AND
						 A.CD_PED = P.CD_PED
		WHERE
			a.CD_EMP    = 1 AND
			a.CD_FILIAL = @CD_FILIAL AND
			P.STS_PED   <> 2 AND
			p.DT_EMI    > @DT_CORTE AND
			p.STS_PED   <> A.STS_PED;


		PRINT 'deleta vinculo errados de pedido com nota danfe '
					+ CONVERT(VARCHAR, GETDATE(), 108);

		DELETE FROM C
		FROM   EST_NF_ENT_DANFE_PROVISORIO_EST_PED_CP C with (nolock)
					 LEFT JOIN EST_PED_CP W with (nolock) ON
						 c.CD_PED = W.CD_PED AND
						 c.CD_FILIAL = W.CD_FILIAL AND
						 c.CD_EMP = W.CD_EMP
		WHERE  c.CD_EMP    = 1 AND
					 c.CD_FILIAL = @CD_FILIAL AND
					 W.CD_EMP IS NULL

		--Deleta pedido vinculado com danfe,diferente do vinculo feito danfe X nf
		DELETE FROM c
		FROM   EST_NF_ENT E with (nolock)
					 INNER JOIN EST_NF_ENT_DANFE_PROVISORIO_EST_NF_ENT P with (nolock) ON
						 E.CD_NF = P.CD_NF AND
						 E.CD_FILIAL = P.CD_FILIAL AND
						 E.CD_EMP = P.CD_EMP
					 INNER JOIN EST_NF_ENT_DANFE_PROVISORIO_EST_PED_CP C with (nolock) ON
						 P.CD_CTR = C.CD_CTR
					 LEFT JOIN EST_NF_ENT_PED_CP W with (nolock) ON
						 E.CD_NF = W.CD_NF AND
						 E.CD_FILIAL = W.CD_FILIAL AND
						 E.CD_EMP = W.CD_EMP
		WHERE  E.CD_EMP    = 1 AND
					 E.DT_ENT    > @DT_CORTE AND
					 E.CD_FILIAL = @CD_FILIAL AND
					 W.CD_EMP IS NULL;

		--vincula o pedido com nota 
		PRINT 'vincula o pedido com nota de entrada '
					+ CONVERT(VARCHAR, GETDATE(), 108);

		INSERT INTO EST_NF_ENT_PED_CP (CD_EMP, CD_FILIAL, CD_PED, CD_NF, DT_CAD) 
		SELECT 
			E.CD_EMP
			,E.CD_FILIAL
			,C.CD_PED
			,E.CD_NF
			,GETDATE() DT_CAD
		FROM
			EST_NF_ENT  E with (nolock)
			INNER JOIN EST_NF_ENT_DANFE_PROVISORIO_EST_NF_ENT P with (nolock) ON
				E.CD_NF = P.CD_NF AND
				E.CD_FILIAL = P.CD_FILIAL AND
				E.CD_EMP = P.CD_EMP
			INNER JOIN EST_NF_ENT_DANFE_PROVISORIO_EST_PED_CP C with (nolock) ON
				P.CD_CTR = C.CD_CTR
			LEFT JOIN EST_NF_ENT_PED_CP W with (nolock) ON
				E.CD_NF = W.CD_NF AND
				E.CD_FILIAL = W.CD_FILIAL AND
				E.CD_EMP = W.CD_EMP
		WHERE
			E.CD_EMP    = 1 AND
			E.DT_ENT    > @DT_CORTE AND
			E.CD_FILIAL = @CD_FILIAL AND
			W.CD_EMP IS NULL

		--Realiza vinculo com pedido
		INSERT INTO EST_NF_ENT_DANFE_PROVISORIO_EST_PED_CP
								(CD_CTR,
								 CD_EMP,
								 CD_FILIAL,
								 CD_PED,
								 CD_USU,
								 DT_CAD)
		SELECT
			D.CD_CTR
			,D.CD_EMP
			,D.CD_FILIAL
			,F.CD_PED
			,1         CD_USU
			,GETDATE() DT_CAD
		FROM
			EST_NF_ENT_DANFE_PROVISORIO d with (nolock)
			LEFT JOIN EST_NF_ENT_DANFE_PROVISORIO_EST_NF_ENT E with (nolock) ON
			D.CD_CTR = E.CD_CTR
			INNER JOIN (SELECT
										F.CD_EMP
										,F.CD_FILIAL
										,F.CD_FORN
										,F.CD_PED_FORN
										,MIN(f.CD_PED) CD_PED
									FROM
										EST_PED_CP F with (nolock)
										join est_ped_cp_it i with (nolock) on 
											f.cd_emp = i.cd_emp and
											f.cd_filial = i.cd_filial and
											f.cd_ped = i.cd_ped
										LEFT JOIN EST_PED_CP_PED_CP_FORN_VINCULADO V ON V.CD_EMP=F.CD_EMP AND V.CD_FILIAL=F.CD_FILIAL AND V.CD_PED_VINC=F.CD_PED
									WHERE
									 LEN(F.CD_PED_FORN)  > 2 AND
									 F.STS_PED IN( 0, 1 )
									 AND V.CD_PED_VINC IS NULL
									GROUP  BY
									 F.CD_EMP
									 ,F.CD_FILIAL
									 ,F.CD_FORN
									 ,F.CD_PED_FORN
									 HAVING (SUM(DBO.[UFD_EST_PED_CP_IT_SLD_DANFE] (F.CD_EMP,F.CD_FILIAL,F.CD_PED,I.CD_PROD,1,0)) >= @ConsideraDanfeEmpresa)
									 ) F ON
				D.CD_EMP = F.CD_EMP AND
				D.CD_FILIAL = F.CD_FILIAL AND
				D.CD_FORN = F.CD_FORN AND
				D.CD_PED_FORN = CONVERT (VARCHAR, F.CD_PED_FORN)
			LEFT JOIN EST_NF_ENT_DANFE_PROVISORIO_EST_PED_CP C with (nolock) ON
				D.CD_CTR = C.CD_CTR
		WHERE
			D.DT_EMIS_NF > @DT_CORTE AND
			E.CD_EMP IS NULL AND
			c.CD_EMP IS NULL AND
			D.CD_EMP     = 1 AND
			D.CD_FILIAL  = @CD_FILIAL AND
			C.CD_EMP IS NULL;

/*************************************************************************************************************************************/
		 --Remove vinculo de pedido sem itens
		  DELETE FROM CP 
		  FROM 
			  EST_NF_ENT_DANFE_PROVISORIO_EST_PED_CP CP
			  LEFT JOIN EST_PED_CP_IT I ON 
			  CP.CD_EMP		=I.CD_EMP AND
			  CP.CD_PED		=I.CD_PED AND
			  CP.CD_FILIAL	=I.CD_FILIAL
		  WHERE
			  I.CD_EMP IS NULL
			  AND CP.CD_FILIAL  = @CD_FILIAL 
			  AND CP.CD_EMP=1;

/*************************************************************************************************************************************/
/*************************************************************************************************************************************/
		PRINT 'refazendo o saldo de cancelamento de itens '
					+ CONVERT(VARCHAR, GETDATE(), 108);

		--refazendo o saldo de cancelamento de itens
		INSERT INTO EST_PED_CP_IT_CANCEL_SLD (CD_EMP,CD_FILIAL,CD_PED,CD_PROD,CD_USU,QT_PROD,DT_CANCEL, HIST, DT_HR_CANCEL)
		SELECT
			V.CD_EMP
			,V.CD_FILIAL
			,V.CD_PED
			,V.CD_PROD
			,V.CD_USU
			,V.QT_PROD
			,V.DT_CANCEL
			, 'P_EST_NF_ENT_DANFE_PROVISORIO_BLOQUEIO_PENDENTE' HIST
			, GETDATE()              DT_HR
		FROM
			(SELECT
				 I.CD_EMP
				 ,I.CD_FILIAL
				 ,V.CD_PED                    CD_PED
				 ,I.CD_PROD
				 ,1                           CD_USU
				 ,SUM(( I.QT_IT * I.QT_EMB )) QT_PROD
				 ,GETDATE()                   DT_CANCEL
			 FROM
				 EST_PED_CP_IT I
				 INNER JOIN EST_PED_CP_PED_CP_FORN_VINCULADO V ON
					 I.CD_EMP = V.CD_EMP AND
					 I.CD_FILIAL = V.CD_FILIAL AND
					 I.CD_PED = V.CD_PED_VINC
				 LEFT JOIN EST_PED_CP_IT_CANCEL_SLD S ON
					 I.CD_EMP = S.CD_EMP AND
					 I.CD_FILIAL = S.CD_FILIAL AND
					 V.CD_PED = S.CD_PED AND
					 I.CD_PROD = S.CD_PROD
			 WHERE
				S.CD_EMP IS NULL AND
				I.CD_EMP    = 1 AND
				I.CD_FILIAL = @CD_FILIAL
			 GROUP  BY
				I.CD_EMP
				,I.CD_FILIAL
				,V.CD_PED
				,I.CD_PROD) V
			INNER JOIN EST_PED_CP_IT W ON
				V.CD_EMP = W.CD_EMP AND
				V.CD_FILIAL = W.CD_FILIAL AND
				V.CD_PED = W.CD_PED AND
				V.CD_PROD = W.CD_PROD
			LEFT JOIN EST_NF_ENT_DANFE_PROVISORIO_EST_PED_CP H ON
				W.CD_EMP = H.CD_EMP AND
				W.CD_FILIAL = H.CD_FILIAL AND
				W.CD_PED = H.CD_PED
		WHERE
			H.CD_EMP IS NULL

		PRINT 'Cria o saldo de cancelamento de itens '
					+ CONVERT(VARCHAR, GETDATE(), 108);

		CREATE TABLE #TMP_CANC_SLD
			(
				 CD_EMP    INT,
				 CD_PROD   INT,
				 CD_PED    INT,
				 CD_FILIAL INT,
				 QT_PED    MONEY
			)

		INSERT INTO #TMP_CANC_SLD
		SELECT
			A.CD_EMP
			,A.CD_PROD
			,A.CD_PED
			,A.CD_FILIAL
			,QT_IT * QT_EMB QT_PED
		FROM
			EST_PED_CP_IT A
			INNER JOIN (SELECT
										CD_EMP
										,CD_FILIAL
										,CD_PED
										,CD_PROD
										,SUM(QT_PROD) QTD_CANC
									FROM
										EST_PED_CP_IT_CANCEL_SLD
									GROUP  BY
									 CD_EMP
									 ,CD_FILIAL
									 ,CD_PED
									 ,CD_PROD) B ON
				A.CD_EMP = B.CD_EMP AND
				A.CD_PROD = B.CD_PROD AND
				A.CD_PED = B.CD_PED AND
				A.CD_FILIAL = B.CD_FILIAL AND
				( QT_IT * QT_EMB ) < QTD_CANC
			INNER JOIN EST_PED_CP P ON
				P.CD_EMP = A.CD_EMP AND
				P.CD_PED = A.CD_PED AND
				P.CD_FILIAL = A.CD_FILIAL
		WHERE
			A.CD_EMP    = 1 AND
			A.CD_FILIAL = @CD_FILIAL AND
			P.DT_EMI    > @DT_CORTE;

		PRINT 'Atualiza o saldo de cancelamento de itens '
					+ CONVERT(VARCHAR, GETDATE(), 108);

		UPDATE B
		SET    QT_PROD = A.QT_PED
		FROM   #TMP_CANC_SLD A
					 INNER JOIN EST_PED_CP_IT_CANCEL_SLD B ON
						 A.CD_EMP = B.CD_EMP AND
						 A.CD_PROD = B.CD_PROD AND
						 A.CD_PED = B.CD_PED AND
						 A.CD_FILIAL = B.CD_FILIAL;

/*********************************************************************************************************************/
/*********************************************************************************************************************/
		CREATE TABLE #RS_FILIAL
			(
				 CD_EMP    INT,
				 CD_FILIAL INT
			)

		CREATE TABLE #RS_PED_VINC
			(
				 CD_CTR_DANFE INT,
				 CD_FORN_NOVO INT,
				 CD_EMP       INT,
				 CD_FILIAL    INT,
				 CD_PED       INT,
				 CD_PED_NOVO  INT,
				 STS_PED      INT,
				 CD_USU		  INT
			);

		CREATE TABLE #RS_DANFE
			(
				 CD_CTR_DANFE INT,
				 PBM          INT,
				 FLAG_IGNORAR_GERA_FINAN INT
			);

		CREATE TABLE #RS_DANFE_LIB
			(
				 CD_CTR  INT,
				 TP_BLOQ INT
			);

		CREATE TABLE #RS_ENT
			(
				 CD_EMP         INT,
				 CD_CTR_DANFE   INT,
				 CD_FILIAL      INT,
				 CD_FORN        INT,
				 CD_PED_FORN    VARCHAR(30),
				 NR_NF          INT,
				 CD_PED         INT,
				 CD_COND_PGTO   INT,
				 VLR_NF         MONEY,
				 VLR_PED        MONEY,
				 VLR_DESC       MONEY,
				 VLR_DESC_FINAN MONEY,
				 DT_FATURAMENTO DATE,
				 BONIFICACAO    TINYINT,
				 VLR_IMPOSTO	 MONEY,
				 FLAG_IGNORAR_GERA_FINAN INT
			);

		CREATE TABLE #RS_ENT_IT
			(
				 CD_EMP            INT,
				 CD_FILIAL         INT,
				 CD_CTR_DANFE      INT,
				 CD_PED            INT,
				 CD_PROD           INT,
				 QT_IT_PED         MONEY,
				 VLR_IT_PED        MONEY,
				 VLR_DESC_PED      MONEY,
				 VLR_IT_DESC_PED   MONEY,
				 QT_IT_DANFE       MONEY,
				 VLR_IT_DANFE      MONEY,
				 VLR_DESC_DANFE    MONEY,
				 VLR_IT_DESC_DANFE MONEY,
				 QT_SALDO		   MONEY
			);

		CREATE TABLE #RS_BLOQ
			(
				 CD_CTR  INT,
				 TP_BLOQ INT,
				 CD_PED  INT
			);

		PRINT 'Criou tabelas auxiliares '
					+ CONVERT(VARCHAR, GETDATE(), 108);

/***************************************************************************************************************************************/
		--		LIBERANDO A ENTRADA DE DANFES PBM
/***************************************************************************************************************************************/
		--DANFE PBM - REPOSICAO AUTOMATICA
		
		SET @sqlCmd = 'INSERT INTO #RS_DANFE 
		SELECT 
			D.CD_CTR
			,1 PBM
			,0 AS FLAG_IGNORAR_GERA_FINAN
		FROM
			EST_NF_ENT_DANFE_PROVISORIO D
			INNER JOIN EST_NF_ENT_DANFE_PROVISORIO_PENDENTE Y ON
				D.CD_CTR = Y.CD_CTR
			INNER JOIN V_EST_NF_ENT_DANFE_PROVISORIO_REPOSICAO_PBM P ON
				D.CD_CTR = P.CD_CTR
		WHERE
			D.CD_EMP					 = 1 AND 
			D.CD_FILIAL				 = '+ CONVERT(VARCHAR, @CD_FILIAL ) + ' AND 
			P.PERC_ATEND                   = 100'
		EXEC (@sqlCmd ); 



		PRINT 'Liberou a entrada de danfes pbm '
					+ CONVERT(VARCHAR, GETDATE(), 108);

		UPDATE D
		SET    FLAG_LIBERA_ENTRADA_SEM_PEDIDO = 1, 
			   FLAG_REPOSICAO_PBM =1
		FROM   EST_NF_ENT_DANFE_PROVISORIO D
					 INNER JOIN #RS_DANFE Y ON
						 D.CD_CTR = Y.CD_CTR_DANFE
		WHERE
			Y.PBM = 1;

		DELETE FROM D
		FROM   EST_NF_ENT_DANFE_PROVISORIO_SEM_PEDIDO D
					 INNER JOIN #RS_DANFE Y ON
						 D.CD_CTR = Y.CD_CTR_DANFE
		WHERE  Y.PBM = 1;

		PRINT 'Liberou a entrada de danfes pbm '
					+ CONVERT(VARCHAR, GETDATE(), 108);

		INSERT INTO EST_NF_ENT_DANFE_PROVISORIO_EST_PED_CP
								(CD_CTR, CD_EMP, CD_FILIAL, CD_PED, CD_USU, DT_CAD)
		SELECT
			D.CD_CTR
			,P.CD_EMP
			,P.CD_FILIAL
			,P.CD_PED
			,1 CD_USU
			,GETDATE()
		FROM
			EST_NF_ENT_DANFE_PROVISORIO D
			CROSS apply(SELECT TOP 1
										p.CD_EMP
										,p.CD_FILIAL
										,p.CD_PED_FORN
										,p.CD_FORN
										,p.CD_PED
										,P.CD_USU
									FROM
										EST_PED_CP P
										join est_ped_cp_it i on 
											p.cd_emp = i.cd_emp and
											p.cd_filial = i.cd_filial and
											p.cd_ped = i.cd_ped
										LEFT JOIN EST_PED_CP_PED_CP_FORN_VINCULADO V ON V.CD_EMP=P.CD_EMP AND V.CD_FILIAL=P.CD_FILIAL AND V.CD_PED_VINC=P.CD_PED
									WHERE
									 LEN(P.CD_PED_FORN)  > 2 AND
									 P.STS_PED     IN (0,1) AND
									 P.CD_EMP      = 1 AND
									 P.CD_FILIAL   = @CD_FILIAL AND
									 D.CD_EMP      = P.CD_EMP AND
									 D.CD_FILIAL   = P.CD_FILIAL AND
									 D.CD_PED_FORN = P.CD_PED_FORN AND
									 D.CD_FORN     = P.CD_FORN
									 AND (DBO.[UFD_EST_PED_CP_IT_SLD_DANFE] (P.CD_EMP,P.CD_FILIAL,P.CD_PED,I.CD_PROD,1,0) >= @ConsideraDanfeEmpresa)
									 AND V.CD_PED_VINC IS NULL
									ORDER  BY
									 P.CD_PED) P
			INNER JOIN #RS_DANFE Y ON
				D.CD_CTR = Y.CD_CTR_DANFE
			LEFT JOIN EST_NF_ENT_DANFE_PROVISORIO_EST_PED_CP W ON
				D.CD_CTR = W.CD_CTR
		WHERE
			W.CD_EMP IS NULL AND
			D.CD_PED_FORN > '0' AND
			Y.PBM = 1;

		DELETE FROM #RS_DANFE
		WHERE  PBM = 1;

		PRINT 'Vinculo de pedido com danfe '
					+ CONVERT(VARCHAR, GETDATE(), 108);

/***************************************************************************************************************************************/
		--		Carrega as filiais liberadas 
/***************************************************************************************************************************************/
		INSERT INTO #RS_FILIAL
		SELECT
			CD_EMP
			,CD_FILIAL
		FROM
			PRC_FILIAL
		WHERE
			CD_EMP    = 1 AND
			CD_FILIAL = ( CASE WHEN @CD_FILIAL > 0 THEN @CD_FILIAL
										ELSE CD_FILIAL
										END );

/***************************************************************************************************************************************/
		-- CARREGA OS DANFES QUE VAO PARTICIPAR DA ANALISE
/***************************************************************************************************************************************/
		INSERT INTO #RS_DANFE
		SELECT
			d.CD_CTR
			,0 PBM
			,ISNULL(P.FLAG_IGNORAR_GERA_FINAN,0)
		FROM
			EST_NF_ENT_DANFE_PROVISORIO D
			INNER JOIN EST_NF_ENT_DANFE_PROVISORIO_PENDENTE Y ON
				d.CD_CTR = Y.CD_CTR
			INNER JOIN #RS_FILIAL F ON
				d.CD_FILIAL = F.CD_FILIAL AND
				d.CD_EMP = F.CD_EMP
			INNER JOIN PG_FORN P ON
				D.CD_EMP = P.CD_EMP AND
				D.CD_FORN = P.CD_FORN
		WHERE FLAG_LIBERA_ENTRADA_SEM_PEDIDO <> 1

		--if @cd_ctr_danfe >0 
		--begin
		--	INSERT INTO #RS_DANFE
		--	SELECT
		--		d.CD_CTR
		--		,0 PBM
		--		,ISNULL(P.FLAG_IGNORAR_GERA_FINAN,0)
		--	FROM
		--		EST_NF_ENT_DANFE_PROVISORIO D
				
		--		INNER JOIN #RS_FILIAL F ON
		--			d.CD_FILIAL = F.CD_FILIAL AND
		--			d.CD_EMP = F.CD_EMP
		--		INNER JOIN PG_FORN P ON
		--			D.CD_EMP = P.CD_EMP AND
		--			D.CD_FORN = P.CD_FORN
		--	WHERE FLAG_LIBERA_ENTRADA_SEM_PEDIDO <> 1
		--	and d.CD_CTR = @cd_ctr_danfe
		--end


		INSERT INTO #RS_DANFE_LIB
		SELECT
			D.CD_CTR_DANFE
			,B.TIPO_BLQ
		FROM
			#RS_DANFE D
			INNER JOIN EST_NF_ENT_DANFE_PROVISORIO_LIBERACAO_TIPO_BLQ B ON
				D.CD_CTR_DANFE = B.CD_CTR
				 
		PRINT 'Carregou os danfes que vao participar da analise '
					+ CONVERT(VARCHAR, GETDATE(), 108);

/***************************************************************************************************************************************/
	--	CRIA O VINCULO DO DANFE COM O PEDIDO DE COMPRAS
	/***************************************************************************************************************************************/
	BEGIN TRY
			----------->>>>>> 
			--INSERT INTO EST_NF_ENT_DANFE_PROVISORIO_EST_PED_CP
			--						(CD_CTR, CD_EMP,CD_FILIAL, CD_PED, CD_USU, DT_CAD)
			SELECT
				 D.CD_CTR
				,P.CD_EMP
				,P.CD_FILIAL
				,MIN(P.CD_PED) CD_PED
				,1 CD_USU
				,GETDATE() DT_CAD

				INTO #TMP_EST_NF_ENT_DANFE_PROVISORIO_EST_PED_CP
			FROM
				EST_NF_ENT_DANFE_PROVISORIO D
				INNER JOIN #RS_DANFE R ON
					D.CD_CTR = R.CD_CTR_DANFE
				CROSS APPLY(SELECT TOP 1
											p.CD_EMP
											,p.CD_FILIAL
											,p.CD_PED_FORN
											,p.CD_FORN
											,p.CD_PED
											,P.CD_USU
										FROM
											EST_PED_CP P 
											JOIN V_PG_FORN_VINCULADO V ON
											P.CD_FORN = V.CD_FORN AND
											D.CD_FORN = V.CD_FORN_VINCULADO 
											join est_ped_cp_it i on 
												p.cd_emp = i.cd_emp and
												p.cd_filial = i.cd_filial and
												p.cd_ped = i.cd_ped
										LEFT JOIN EST_PED_CP_PED_CP_FORN_VINCULADO V1 ON V1.CD_EMP=P.CD_EMP AND V1.CD_FILIAL=P.CD_FILIAL AND V1.CD_PED_VINC=P.CD_PED
										WHERE
											 P.STS_PED     IN (0,1) AND
											 LEN(P.CD_PED_FORN)  > 2 AND
											 P.CD_EMP      = 1 AND
											 P.CD_FILIAL   = @CD_FILIAL AND
											 D.CD_EMP      = P.CD_EMP AND
											 D.CD_FILIAL   = P.CD_FILIAL AND
											 D.CD_PED_FORN = P.CD_PED_FORN AND
											 --pASSA A DAR 2 DIAS 
											 DATEADD(DAY,5,D.DT_EMIS_NF)  >= P.DT_EMI
											AND (DBO.[UFD_EST_PED_CP_IT_SLD_DANFE] (P.CD_EMP,P.CD_FILIAL,P.CD_PED,I.CD_PROD,1,0) >= @ConsideraDanfeEmpresa)
											AND V1.CD_PED_VINC IS NULL
										ORDER  BY P.CD_PED
										
										) P
				LEFT JOIN EST_NF_ENT_DANFE_PROVISORIO_EST_PED_CP W ON
				D.CD_CTR = W.CD_CTR 
			
			WHERE
				len (D.CD_PED_FORN)  > 0 AND
				R.CD_CTR_DANFE > 0 AND
				W.CD_EMP IS NULL
			GROUP  BY
				D.CD_CTR
				,P.CD_EMP
				,P.CD_FILIAL
				,P.CD_USU;
					
					
			INSERT INTO EST_NF_ENT_DANFE_PROVISORIO_EST_PED_CP
									(CD_CTR, CD_EMP,CD_FILIAL, CD_PED, CD_USU, DT_CAD)
			SELECT * FROM #TMP_EST_NF_ENT_DANFE_PROVISORIO_EST_PED_CP;

			PRINT 'Achar o pedido do Danfe ' + CONVERT(VARCHAR, GETDATE(), 108);

			--Achar o pedido do Danfe
			INSERT INTO EST_NF_ENT_DANFE_PROVISORIO_EST_PED_CP
									(CD_CTR,
									 CD_EMP,
									 CD_FILIAL,
									 CD_PED,
									 CD_USU,
									 DT_CAD)
			SELECT
				D.CD_CTR
				,P.CD_EMP
				,P.CD_FILIAL
				,P.CD_PED
				,1 CD_USU
				,GETDATE()
				
			FROM
				EST_NF_ENT_DANFE_PROVISORIO D
				INNER JOIN #RS_DANFE R ON
				D.CD_CTR = R.CD_CTR_DANFE
				CROSS apply(SELECT TOP 1
											p.CD_EMP
											,p.CD_FILIAL
											,p.CD_PED_FORN
											,p.CD_FORN
											,p.CD_PED
											,p.CD_USU
										FROM
											EST_PED_CP P
											join est_ped_cp_it i on 
											p.cd_emp = i.cd_emp and
											p.cd_filial = i.cd_filial and
											p.cd_ped = i.cd_ped
											LEFT JOIN EST_PED_CP_PED_CP_FORN_VINCULADO V ON V.CD_EMP=P.CD_EMP AND V.CD_FILIAL=P.CD_FILIAL AND V.CD_PED_VINC=P.CD_PED
										WHERE
										 P.STS_PED            IN (0,1) AND
										 LEN(P.CD_PED_FORN)  > 2 AND
										 P.CD_EMP                 = 1 AND
										 P.CD_FILIAL              = @CD_FILIAL AND
										 ISNULL(P.CD_CTR_DANFE, 0) = 0 AND
										 D.CD_EMP                 = P.CD_EMP AND
										 D.CD_FILIAL              = P.CD_FILIAL AND
										 D.CD_PED_FORN            = P.CD_PED_FORN AND
										 D.CD_FORN                = P.CD_FORN
										 AND (DBO.[UFD_EST_PED_CP_IT_SLD_DANFE] (P.CD_EMP,P.CD_FILIAL,P.CD_PED,I.CD_PROD,1,0) >= @ConsideraDanfeEmpresa)
										 AND V.CD_PED_VINC IS NULL
										ORDER  BY
										 P.CD_PED) P
				LEFT JOIN EST_NF_ENT_DANFE_PROVISORIO_EST_PED_CP W ON
					D.CD_CTR = W.CD_CTR
			WHERE
				len(D.CD_PED_FORN) > 0 AND
				W.CD_EMP IS NULL;

			PRINT 'Cria o vinculo do danfe com o pedido de compras ' + CONVERT(VARCHAR, GETDATE(), 108);
			

			INSERT INTO EST_NF_ENT_DANFE_PROVISORIO_EST_PED_CP
									(CD_CTR,
									 CD_EMP,
									 CD_FILIAL,
									 CD_PED,
									 CD_USU,
									 DT_CAD)
			SELECT
				D.CD_CTR
				,P.CD_EMP
				,P.CD_FILIAL
				,P.CD_PED
				,1 CD_USU
				,GETDATE()
			FROM
				EST_NF_ENT_DANFE_PROVISORIO D
				INNER JOIN #RS_DANFE R ON
					D.CD_CTR = R.CD_CTR_DANFE
				INNER JOIN EST_NF_ENT_DANFE_PROVISORIO_SEM_PEDIDO Y ON
					D.CD_CTR = Y.CD_CTR
				CROSS apply(SELECT TOP 1
											p.CD_EMP
											,p.CD_FILIAL
											,p.CD_PED_FORN
											,p.CD_FORN
											,p.CD_PED
											,p.CD_USU
										FROM
											EST_PED_CP P
											join est_ped_cp_it i on 
											p.cd_emp = i.cd_emp and
											p.cd_filial = i.cd_filial and
											p.cd_ped = i.cd_ped
											LEFT JOIN EST_PED_CP_PED_CP_FORN_VINCULADO V ON V.CD_EMP=P.CD_EMP AND V.CD_FILIAL=P.CD_FILIAL AND V.CD_PED_VINC=P.CD_PED
										WHERE
											 P.STS_PED             IN (0,1) AND
											 P.CD_EMP                 = 1 AND
											 LEN(P.CD_PED_FORN)  > 2 AND
											 P.CD_FILIAL              = @CD_FILIAL AND
											 ISNULL(P.CD_CTR_DANFE, 0) = 0 AND
											 D.CD_EMP                 = P.CD_EMP AND
											 D.CD_FILIAL              = P.CD_FILIAL AND
											 D.CD_PED_FORN            = P.CD_PED_FORN AND
											 D.CD_FORN                = P.CD_FORN
											 AND (DBO.[UFD_EST_PED_CP_IT_SLD_DANFE] (P.CD_EMP,P.CD_FILIAL,P.CD_PED,I.CD_PROD,1,0) >= @ConsideraDanfeEmpresa)
											 AND V.CD_PED_VINC IS NULL
										ORDER  BY
											P.CD_PED) P
				LEFT JOIN EST_NF_ENT_DANFE_PROVISORIO_EST_PED_CP W ON
					D.CD_CTR = W.CD_CTR
			WHERE
				len(D.CD_PED_FORN) > 0 AND
				W.CD_EMP IS NULL;

			PRINT 'Gerar um pedido de acordo com o danfe '
						+ CONVERT(VARCHAR, GETDATE(), 108);

	/***************************************************************************************************************************************/
			-- se for pedido de fornecedor vinculado
			-- Gerar um pedido de acordo com o danfe...  para o fornecedor novo
	/***************************************************************************************************************************************/


			INSERT INTO #RS_PED_VINC
			SELECT
				D.CD_CTR
				,D.CD_FORN FORN_NOVO
				,P.CD_EMP
				,P.CD_FILIAL
				,P.CD_PED
				,0 CD_PED_NOVO
				,0 STS 
				,P.CD_USU
			FROM
				EST_NF_ENT_DANFE_PROVISORIO D
				INNER JOIN EST_NF_ENT_DANFE_PROVISORIO_EST_PED_CP DP ON
				D.CD_CTR = DP.CD_CTR

				INNER JOIN #RS_DANFE R ON
				D.CD_CTR = R.CD_CTR_DANFE

				LEFT JOIN EST_PED_CP_PED_CP_FORN_VINCULADO V ON 
				D.CD_CTR = V.CD_CTR_DANFE

				INNER JOIN EST_PED_CP P ON
					D.CD_FORN <> P.CD_FORN AND
					DP.CD_EMP = P.CD_EMP AND
					DP.CD_FILIAL = P.CD_FILIAL AND
					DP.CD_PED = P.CD_PED
				WHERE
					V.CD_EMP IS NULL;
		--	select * from #RS_PED_VINC
			UPDATE P
			SET    CD_PED_NOVO = PED_NOVO
			FROM   #RS_PED_VINC P
						 INNER JOIN (SELECT
											v.CD_EMP
											,v.CD_FILIAL
											,v.CD_PED
											,V.CD_CTR_DANFE
											,ISNULL(ULT_PED, 0)
											+ ROW_NUMBER() OVER (ORDER BY v.CD_EMP, v.CD_FILIAL, v.CD_PED) PED_NOVO
										FROM
											#RS_PED_VINC v
											LEFT JOIN (SELECT
																	CD_EMP
																	,CD_FILIAL
																	,MAX(CD_PED) ULT_PED
																FROM
																	EST_PED_CP
																GROUP  BY
																	CD_EMP
																	,CD_FILIAL) m ON
									v.CD_EMP = m.CD_EMP AND
									v.CD_FILIAL = m.CD_FILIAL) N ON
							 P.CD_EMP = N.CD_EMP AND
							 P.CD_PED = N.CD_PED AND
							 P.CD_CTR_DANFE = N.CD_CTR_DANFE AND
							 P.CD_FILIAL = N.CD_FILIAL;

			/***************************************************************************************************************************************/
			INSERT INTO EST_PED_CP
									(CD_EMP,
									 CD_FILIAL,
									 CD_PED,
									 CD_FORN,
									 DT_EMI,
									 VLR_PED,
									 VLR_TOT_PROD,
									 VLR_DESC,
									 DT_PREV_ENT,
									 VLR_ENCG_FIN,
									 PERC_ICMS_ENCG_FIN,
									 VLR_ICMS,
									 VLR_IPI,
									 VLR_BASE_SUBS,
									 VLR_ICMS_SUBS,
									 CD_NT_MOV,
									 STS_PED,
									 VLR_BASE_ICMS,
									 CD_USU,
									 DT_CAD,
									 DT_ULT_ATU,
									 DT_BAIXA,
									 VLR_FRETE,
									 NF_IPI_BASE_CALC,
									 ENCG_TRIB,
									 NAO_CONSTAR_PEND_ENTR,
									 DT_CANCEL,
									 CD_USU_CANCEL,
									 NR_REQ_FORN,
									 TP_FRETE,
									 CONHECIMENTO,
									 CALC_SUBS_PMC,
									 PERC_REDU_SUBS_PMC,
									 DT_PREV_ENT_ANT,
									 CD_PED_FORN,
									 CD_TIPO_FATURAMENTO,
									 HORA_PREV_ENT,
									 QT_VOL,
									 FLAG_GERAR_CROSS,
									 CD_COND_PGTO,
									 CD_CTR_DANFE,
									 ORIGEM_PED,
									 APLICATIVO,
									 VERSAO_APLICATIVO,
									 DT_FATURAMENTO)
			SELECT
				P.CD_EMP
				,P.CD_FILIAL
				,V.CD_PED_NOVO        CD_PED
				,V.CD_FORN_NOVO       CD_FORN
				,DT_EMI
				,VLR_PED
				,VLR_TOT_PROD
				,VLR_DESC
				,DT_PREV_ENT
				,VLR_ENCG_FIN
				,PERC_ICMS_ENCG_FIN
				,VLR_ICMS
				,VLR_IPI
				,VLR_BASE_SUBS
				,VLR_ICMS_SUBS
				,CD_NT_MOV
				,P.STS_PED
				,VLR_BASE_ICMS
				,p.CD_USU
				,GETDATE()            DT_CAD
				,DT_ULT_ATU
				,DT_BAIXA
				,VLR_FRETE
				,NF_IPI_BASE_CALC
				,ENCG_TRIB
				,NAO_CONSTAR_PEND_ENTR
				,DT_CANCEL
				,CD_USU_CANCEL
				,NR_REQ_FORN
				,TP_FRETE
				,CONHECIMENTO
				,CALC_SUBS_PMC
				,PERC_REDU_SUBS_PMC
				,DT_PREV_ENT_ANT
				,CD_PED_FORN
				,CD_TIPO_FATURAMENTO
				,HORA_PREV_ENT
				,QT_VOL
				,FLAG_GERAR_CROSS
				,CD_COND_PGTO
				,V.CD_CTR_DANFE
				,ORIGEM_PED
				,'Orig_Ped_Vinculado' APLICATIVO
				,VERSAO_APLICATIVO
				,DT_FATURAMENTO
			FROM
				EST_PED_CP P
				INNER JOIN #RS_PED_VINC V ON
					P.CD_EMP = V.CD_EMP AND
					P.CD_FILIAL = V.CD_FILIAL AND
					P.CD_PED = V.CD_PED;

			INSERT INTO EST_PED_CP_IT (CD_EMP, CD_FILIAL, CD_PED, CD_PROD, SEQ_ITEM, VLR_IT,
									 QT_IT,									 CD_TRIB,
									 PERC_IPI,									 VLR_CUSTO,
									 VLR_BASE_SUBS,									 VLR_ICMS_SUBS,
									 ALIQ_ICMS,									 VLR_BASE_ICMS,
									 CD_NT_OP,									 VLR_IPI,									 VLR_ICMS,									 PERC_DESC,									 VLR_DESC,
									 PERC_IVA,									 QT_EMB,
									 PERC_IPI_CUSTO,
									 PERC_DESC_FINAN,
									 CD_COND_COMPRA)
			SELECT
				I.CD_EMP
				,I.CD_FILIAL
				,V.CD_PED_NOVO                                    CD_PED
				,I.CD_PROD
				,D.CD_CTR_IT                                      SEQ_ITEM
				,I.VLR_IT
				,
				--D.QTDE_PROD, 
				CASE WHEN D.QTDE_PROD > ( I.QT_IT * CASE WHEN ISNULL(I.QT_EMB,0)=0 THEN 1 ELSE I.QT_EMB END ) THEN I.QT_IT
				 ELSE ROUND(D.QTDE_PROD / CASE WHEN ISNULL(I.QT_EMB,0)=0 THEN 1 ELSE I.QT_EMB END, 0)
				 END                                              QT_IT
				,I.CD_TRIB
				,I.PERC_IPI
				,I.VLR_CUSTO
				,I.VLR_BASE_SUBS
				,I.VLR_ICMS_SUBS
				,I.ALIQ_ICMS
				,I.VLR_BASE_ICMS
				,I.CD_NT_OP
				,I.VLR_IPI
				,I.VLR_ICMS
				,I.PERC_DESC
				,( CASE WHEN D.QTDE_PROD > ( I.QT_IT * I.QT_EMB ) THEN I.QT_IT
					 ELSE ROUND(D.QTDE_PROD / ISNULL(I.QT_EMB,0), 0)
					 END * I.VLR_IT ) * (( I.PERC_DESC / 100.000 )) VLR_DESC
				,I.PERC_IVA
				,I.QT_EMB
				,I.PERC_IPI_CUSTO
				,I.PERC_DESC_FINAN
				,I.CD_COND_COMPRA
			FROM
				EST_PED_CP_IT I
				INNER JOIN #RS_PED_VINC V ON
					I.CD_EMP = V.CD_EMP AND
					I.CD_FILIAL = V.CD_FILIAL AND
					I.CD_PED = V.CD_PED
				INNER JOIN (SELECT D.CD_CTR
											,D.CD_PROD
											,ROW_NUMBER()
												 OVER (
													 partition BY D.CD_CTR
													 ORDER BY D.CD_CTR, D.CD_PROD )          CD_CTR_IT
											,SUM (D.QTDE_PROD * ( D.APRES_QT_CP * CASE WHEN ISNULL(D.APRES_EMB_CP, 0) = 0 THEN 1
																														ELSE D.APRES_EMB_CP
																														END )) QTDE_PROD
										FROM
											EST_NF_ENT_DANFE_PROVISORIO_ITENS D
											INNER JOIN #RS_DANFE R ON
												D.CD_CTR = R.CD_CTR_DANFE
										GROUP  BY
										 D.CD_CTR
										 ,D.CD_PROD) D ON
					V.CD_CTR_DANFE = D.CD_CTR AND
					I.CD_PROD = D.CD_PROD;

			 --Remove pedidos sem item..
			 delete from a 
			 from
				 #RS_PED_VINC a
				 left join est_ped_cp_it i on 
				 A.CD_EMP	    = I.CD_EMP AND
				 A.CD_FILIAL	= I.CD_FILIAL AND
				 A.CD_PED_NOVO  = I.CD_PED
			 WHERE
				I.CD_EMP IS NULL


			--CRIA O VINCULO COM O NOVO PEDIDO
			INSERT INTO EST_PED_CP_PED_CP_FORN_VINCULADO
									(CD_EMP,
									 CD_FILIAL,
									 CD_PED,
									 CD_PED_VINC,
									 CD_CTR_DANFE,
									 CD_USU,
									 DT_CAD)
			SELECT
				CD_EMP
				,CD_FILIAL
				,CD_PED
				,CD_PED_NOVO CD_PED_VINC
				,CD_CTR_DANFE
				,CD_USU
				,GETDATE()   DT_CAD
			FROM
				#RS_PED_VINC;

		
			PRINT 'Cancela o saldo gerado pelo novo pedido '
						+ CONVERT(VARCHAR, GETDATE(), 108);

			--CANCELA O SALDO GERADO PELO NOVO PEDIDO
			INSERT INTO EST_PED_CP_IT_CANCEL_SLD
									(CD_EMP,
									 CD_FILIAL,
									 CD_PED,
									 CD_PROD,
									 CD_USU,
									 QT_PROD,
									 DT_CANCEL,
									 HIST, 
									 DT_HR_CANCEL)
			SELECT
				I.CD_EMP
				,I.CD_FILIAL
				,V.CD_PED               CD_PED
				,I.CD_PROD
				,V.CD_USU
				,( I.QT_IT * i.QT_EMB ) QT_PROD
				, GETDATE()              DT_CANCEL
				, 'P_EST_NF_ENT_DANFE_PROVISORIO_BLOQUEIO_PENDENTE'
				, GETDATE()              DT_HR
			FROM
				EST_PED_CP_IT I
				INNER JOIN #RS_PED_VINC V ON
					I.CD_EMP	= V.CD_EMP AND
					I.CD_FILIAL = V.CD_FILIAL AND
					I.CD_PED	= V.CD_PED_NOVO
				LEFT JOIN EST_PED_CP_IT_CANCEL_SLD s ON
					I.CD_EMP	= s.CD_EMP AND
					I.CD_FILIAL = s.CD_FILIAL AND
					I.CD_PED	= S.CD_PED AND
					I.CD_PROD	= S.CD_PROD
			WHERE
				S.CD_EMP IS NULL;

			--Alterar o total dos pedidos gerados 
			PRINT 'Alterar o total dos pedidos gerados '
						+ CONVERT(VARCHAR, GETDATE(), 108);

			UPDATE p
			SET    VLR_TOT_PROD = T.TOT_PROD,
						 VLR_IPI = T.VLR_IPI,
						 VLR_BASE_ICMS = T.VLR_BASE_ICMS,
						 VLR_ICMS = T.VLR_ICMS,
						 VLR_BASE_SUBS = T.VLR_BASE_SUBS,
						 VLR_ICMS_SUBS = T.VLR_ICMS_SUBS,
						 VLR_DESC = T.VLR_DESC,
						 VLR_PED = ( T.TOT_PROD + T.VLR_IPI + T.VLR_ICMS_SUBS
												 + P.VLR_FRETE )
			FROM   EST_PED_CP P
						 INNER JOIN (SELECT
													 I.CD_EMP
													 ,I.CD_FILIAL
													 ,I.CD_PED
													 ,SUM (( I.QT_IT * I.VLR_IT ) - I.VLR_DESC) AS TOT_PROD
													 ,SUM (I.VLR_DESC)                          AS VLR_DESC
													 ,SUM (I.VLR_BASE_ICMS)                     AS VLR_BASE_ICMS
													 ,SUM (I.VLR_ICMS)                          AS VLR_ICMS
													 ,SUM (I.VLR_BASE_SUBS)                     AS VLR_BASE_SUBS
													 ,SUM (I.VLR_ICMS_SUBS)                     AS VLR_ICMS_SUBS
													 ,SUM (I.VLR_IPI)                           AS VLR_IPI
												 FROM
													 #RS_PED_VINC v
													 INNER JOIN EST_PED_CP_IT I ON
														 V.CD_EMP = I.CD_EMP AND
														 V.CD_FILIAL = I.CD_FILIAL AND
														 V.CD_PED_NOVO = I.CD_PED
												 GROUP  BY
													I.CD_EMP
													,I.CD_FILIAL
													,I.CD_PED) T ON
							 P.CD_EMP = T.CD_EMP AND
							 P.CD_FILIAL = T.CD_FILIAL AND
							 P.CD_PED = T.CD_PED;
------------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------------


			--Atualiza o status dos pedidos
			UPDATE V
			SET    V.STS_PED = CASE WHEN dbo.TST_EST_PED_CP_STATUS (V.CD_EMP, V.CD_FILIAL, V.CD_PED) IN ( 'PEDIDO CANCELADO', 'CANCELADO' ) THEN 2
									WHEN dbo.TST_EST_PED_CP_STATUS (V.CD_EMP, V.CD_FILIAL, V.CD_PED) IN ( 'PEDIDO COM ENTREGA TOTAL' )		THEN 3
									ELSE 0 END
			FROM   #RS_PED_VINC v;

			UPDATE P
			SET    STS_PED = V.STS_PED
			FROM   #RS_PED_VINC V
						 INNER JOIN EST_PED_CP P ON
							 V.CD_EMP = P.CD_EMP AND
							 V.CD_FILIAL = P.CD_FILIAL AND
							 V.CD_PED_NOVO = P.CD_PED
			WHERE
				V.STS_PED > 0;

------------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------------
			--Vincula o danfe ao novo pedido gerado
			UPDATE E
			SET    CD_PED = V.CD_PED_NOVO
			FROM   #RS_PED_VINC V
						 INNER JOIN EST_NF_ENT_DANFE_PROVISORIO_EST_PED_CP E ON
							 V.CD_CTR_DANFE = E.CD_CTR;

			DELETE FROM B
			FROM   EST_NF_ENT_DANFE_PROVISORIO A
						 INNER JOIN EST_NF_ENT_DANFE_PROVISORIO_EST_PED_CP B ON
							 A.CD_CTR = B.CD_CTR
						 INNER JOIN EST_PED_CP C ON
							 B.CD_EMP = C.CD_EMP AND
							 B.CD_PED = C.CD_PED AND
							 B.CD_FILIAL = C.CD_FILIAL AND
							 A.CD_FORN <> C.CD_FORN
						 INNER JOIN #RS_DANFE R ON
							 A.CD_CTR = R.CD_CTR_DANFE;


	END TRY

	BEGIN CATCH
			PRINT 'Falha ao tentar criar/vincular pedido de compras'
			PRINT ERROR_MESSAGE()
			RETURN;
	END CATCH

/***************************************************************************************************************************************/
/***************************************************************************************************************************************/

		PRINT 'Analisa o danfe com o pedido de compras '
					+ CONVERT(VARCHAR, GETDATE(), 108);

		INSERT INTO #RS_ENT (CD_EMP,
								 CD_CTR_DANFE,
								 CD_FILIAL,
								 CD_FORN,
								 CD_PED_FORN,
								 NR_NF,
								 CD_PED,
								 CD_COND_PGTO,
								 VLR_NF,
								 VLR_PED,
								 VLR_DESC,
								 VLR_DESC_FINAN,
								 DT_FATURAMENTO,
								 BONIFICACAO,
								 VLR_IMPOSTO,
								 FLAG_IGNORAR_GERA_FINAN)
		SELECT
			D.CD_EMP
			,D.CD_CTR
			,D.CD_FILIAL
			,D.CD_FORN
			,D.CD_PED_FORN
			,D.NR_NF
			,P.CD_PED
			,P.CD_COND_PGTO
			,( d.VLR_PROD_TOT - d.VLR_DESCONTO )
			,p.VLR_TOT_PROD
			,P.VLR_DESC
			,0 VLR_DESC_FINAN
			,D.DT_EMIS_NF DT_FAT
			,CASE WHEN TP_MOV IN( 3, 4, 5 ) THEN 1
			 ELSE 0
			 END                                BONIFICA
			,ISNULL(D.VLR_ICMS_SUBS,0) VLR_IMPOSTO
			,FLAG_IGNORAR_GERA_FINAN
		FROM
			EST_NF_ENT_DANFE_PROVISORIO D
			INNER JOIN #RS_DANFE Y ON
				D.CD_CTR = Y.CD_CTR_DANFE
			INNER JOIN EST_NF_ENT_DANFE_PROVISORIO_EST_PED_CP DP ON
				D.CD_CTR = DP.CD_CTR
			INNER JOIN EST_PED_CP P ON
				DP.CD_EMP = P.CD_EMP AND
				DP.CD_FILIAL = P.CD_FILIAL AND
				DP.CD_PED = P.CD_PED
			JOIN GLB_MOV_OP O ON
				P.CD_NT_MOV = O.CD_MOV_OP
		WHERE
			D.CD_EMP = 1;

			if @cd_ctr_danfe >0
				select * from #RS_ENT where cd_ctr_danfe=@cd_ctr_danfe
/***************************************************************************************************************************************/
		-- DANFE SEM PEDIDO 
		/***************************************************************************************************************************************/
		PRINT 'Danfe sem pedido  '
					+ CONVERT(VARCHAR, GETDATE(), 108);

		INSERT INTO #RS_BLOQ
								(CD_CTR,
								 TP_BLOQ,
								 CD_PED)
		SELECT
			D.CD_CTR CD_CTR_DANFE
			,3
			,-- 
			0 CD_PED
		FROM
			EST_NF_ENT_DANFE_PROVISORIO D
			INNER JOIN PG_FORN F ON
				D.CD_EMP = F.CD_EMP AND
				D.CD_FORN = F.CD_FORN AND
				F.FLAG_ENTRAR_NF_SEM_VINC_PEDIDO = 0 --QUE NAO PERMITE ENTRADA SEM PEDIDO.
			INNER JOIN #RS_DANFE Y ON
				D.CD_CTR = Y.CD_CTR_DANFE
			LEFT JOIN EST_NF_ENT_DANFE_PROVISORIO_EST_PED_CP DP ON
				D.CD_CTR = DP.CD_CTR
			LEFT JOIN #RS_DANFE_LIB L ON
				D.CD_CTR = L.CD_CTR AND
				L.TP_BLOQ = 3
		WHERE
			DP.CD_CTR IS NULL AND
			L.CD_CTR IS NULL --> QUE NAO ESTEJA LIBERADO..
			AND D.FLAG_LIBERA_ENTRADA_SEM_PEDIDO = 0;

/***************************************************************************************************************************************/
/***************************************************************************************************************************************/
/***************************************************************************************************************************************/


/***************************************************************************************************************************************/
/***************************************************************************************************************************************/
		--EST_NF_ENT_DANFE_PROVISORIO_BLOQUEIO_PENDENTE 
		--TIPO_BLQ
		--	0 - NÃO ENCONTRADO
		--	1 - ENCONTRADO E OK
		--	2 - DIVERGENCIA A MAIOR
		-- 3 SEM XPED
		-- 4 CONDICOES DE PAGAMENTO
		-- 5 VALOR PAGAMENTO DIVERGENTE
		-- 6 DT VENCIMENTO INVALIDO
		-- 7 QTDE ITEM DIVERGENTE 
		-- 8 VLR ITEM DIVERGENTE
		-- 9 VLR DESC PED DIVERGENTE
/**********************************************************************************************************************************/
		-- VALIDA A CONDICAO DE PAGAMENTOS
/**********************************************************************************************************************************/

IF @FLAG_DESATIVAR_DIVERG_COND_PGTO_PEDIDO=0
BEGIN
		-- CONDICAO PAGTO INVALIDA
		INSERT INTO #RS_BLOQ (CD_CTR,
								 TP_BLOQ,
								 CD_PED)
		SELECT
			A.CD_CTR_DANFE
			,4 TP_BLOQ
			,A.CD_PED
		FROM
			#RS_ENT A
			LEFT JOIN GLB_COND_PGTO B ON
				A.CD_EMP = B.CD_EMP AND
				A.CD_COND_PGTO = B.CD_COND_PGTO
			LEFT JOIN #RS_DANFE_LIB L ON
				A.CD_CTR_DANFE = L.CD_CTR AND
				L.TP_BLOQ = 4
		WHERE
			B.CD_COND_PGTO IS NULL AND
			A.BONIFICACAO = 0 AND
			L.CD_CTR IS NULL
			AND A.FLAG_IGNORAR_GERA_FINAN =0; --> QUE NAO ESTEJA LIBERADO..

		-- VALOR PAGAMENTO DIVERGENTE
		--DECLARE @VLR_DIV MONEY =0.02
		if @FLAG_DESATIVAR_DIVERG_VALOR_PGTO_PEDIDO =0
		BEGIN
			INSERT INTO #RS_BLOQ
									(CD_CTR,
									 TP_BLOQ,
									 CD_PED)
			SELECT
				A.CD_CTR_DANFE
				,5 TP_BLOQ
				,A.CD_PED
			FROM
				#RS_ENT A
				LEFT JOIN #RS_DANFE_LIB L ON
					A.CD_CTR_DANFE = L.CD_CTR AND
					L.TP_BLOQ = 5
			WHERE
				(( A.VLR_NF - A.VLR_IMPOSTO)- A.VLR_PED ) > @VLR_DIV AND
				A.BONIFICACAO          = 0 
				AND L.CD_CTR IS NULL
				AND A.FLAG_IGNORAR_GERA_FINAN =0; --> QUE NAO ESTEJA LIBERADO..

  

			INSERT INTO #RS_BLOQ
									(CD_CTR,
									 TP_BLOQ,
									 CD_PED)
			SELECT
				A.CD_CTR_DANFE
				,5 TP_BLOQ
				,A.CD_PED
			FROM
				EST_NF_ENT_DANFE_PROVISORIO_DUPLICATA D
				INNER JOIN #RS_ENT A ON
					D.CD_CTR = A.CD_CTR_DANFE
				LEFT JOIN #RS_DANFE_LIB L ON
					A.CD_CTR_DANFE = L.CD_CTR AND
					L.TP_BLOQ = 5
			WHERE
				(	( ( D.VLR_TITULO-A.VLR_IMPOSTO) - A.VLR_PED )      > @VLR_DIV  OR
					( A.VLR_DESC_FINAN - D.VLR_DESC ) > @VLR_DIV 
					) AND
				A.BONIFICACAO = 0 
				AND L.CD_CTR IS NULL
				AND A.FLAG_IGNORAR_GERA_FINAN =0; --> QUE NAO ESTEJA LIBERADO..
		END

		INSERT INTO #RS_BLOQ
								(CD_CTR,
								 TP_BLOQ,
								 CD_PED)
		SELECT
			A.CD_CTR_DANFE
			,4 TP_BLOQ
			,--CONDICAO PGTO DUPLICATA
			A.CD_PED
		FROM
			#RS_ENT A
			LEFT JOIN EST_NF_ENT_DANFE_PROVISORIO_DUPLICATA D ON
				A.CD_CTR_DANFE = D.CD_CTR
			LEFT JOIN #RS_DANFE_LIB L ON
				A.CD_CTR_DANFE = L.CD_CTR AND
				L.TP_BLOQ = 4
		WHERE
			D.CD_CTR IS NULL 
			AND A.BONIFICACAO = 0 
			AND L.CD_CTR IS NULL
			AND A.FLAG_IGNORAR_GERA_FINAN =0; --> QUE NAO ESTEJA LIBERADO..
		
		--  DT VENCIMENTO INVALIDA.
		INSERT INTO #RS_BLOQ
								(CD_CTR,
								 TP_BLOQ,
								 CD_PED)
		SELECT
			A.CD_CTR_DANFE
			,6 TP_BLOQ
			,A.CD_PED
		FROM
			EST_NF_ENT_DANFE_PROVISORIO_DUPLICATA D
			INNER JOIN #RS_ENT A ON
				D.CD_CTR = A.CD_CTR_DANFE
			INNER JOIN GLB_COND_PGTO_CPL B ON
				A.CD_EMP = B.CD_EMP AND
				A.CD_COND_PGTO = B.CD_COND_PGTO AND
				( D.CD_CTR_TITULO + 1 ) = B.NR_VENCTO
			LEFT JOIN #RS_DANFE_LIB L ON
				A.CD_CTR_DANFE = L.CD_CTR AND
				L.TP_BLOQ = 6
		WHERE
			L.CD_CTR IS NULL --> QUE NAO ESTEJA LIBERADO..
			AND A.BONIFICACAO = 0 
			AND D.DT_VENCTO  < DATEADD(DAY, B.DIAS_VENCTO, DT_FATURAMENTO)
			AND A.FLAG_IGNORAR_GERA_FINAN =0;
END		 

/**********************************************************************************************************************************/
		-- VALIDA O CABECALHO DO PEDIDO.
		/**********************************************************************************************************************************/
		PRINT 'Vincula o cabeçalho do pedido  '
					+ CONVERT(VARCHAR, GETDATE(), 108);
	 
		INSERT INTO #RS_ENT_IT (CD_EMP,
								 CD_FILIAL,
								 CD_CTR_DANFE,
								 CD_PED,
								 CD_PROD,
								 QT_IT_PED,
								 VLR_IT_PED,
								 VLR_DESC_PED,
								 VLR_IT_DESC_PED,
								 QT_IT_DANFE,
								 VLR_IT_DANFE,
								 VLR_DESC_DANFE,
								 VLR_IT_DESC_DANFE,
								 QT_SALDO)
		SELECT
			I.CD_EMP
			,D.CD_FILIAL
			,D.CD_CTR_DANFE
			,D.CD_PED
			,D.CD_PROD
			,ROUND(I.QT_IT * CASE WHEN I.QT_EMB=0 THEN 1 ELSE I.QT_EMB END - ISNULL(C.QT_PROD,0) * CASE WHEN I.QT_EMB=0 THEN 1 ELSE I.QT_EMB END, 2) QT_IT
			,ROUND(I.VLR_IT, 2)
			,ROUND(I.VLR_DESC, 2)
			,ROUND(I.VLR_DESC / ( ROUND(I.QT_IT *  CONVERT(DECIMAL(13, 4), CASE WHEN I.QT_EMB=0 THEN 1 ELSE I.QT_EMB END), 4) ), 4)
			,D.QT_IT
			,D.VLR_IT
			,D.VLR_PROD_DESC
			,ROUND(D.VLR_PROD_DESC /  D.QT_IT, 4)
			--,QT_SALDO = ROUND(I.QT_IT * CASE WHEN I.QT_EMB=0 THEN 1 ELSE I.QT_EMB END - ISNULL(C.QT_PROD,0), 2) - (ISNULL(QT_IT_VINCULADO,0)+ISNULL(QT_ENTROU,0) - D.QT_IT)
			,QT_SALDO = dbo.UFD_EST_PED_CP_IT_SLD_DANFE(I.CD_EMP,D.CD_FILIAL,D.CD_PED,D.CD_PROD,1,D.CD_CTR_DANFE)
		FROM
			EST_PED_CP_IT I
			INNER JOIN (SELECT
										A.CD_EMP
										,A.CD_FILIAL
										,A.CD_CTR_DANFE
										,A.CD_PED
										,D.CD_PROD
										,ROUND(AVG(( D.VLR_PROD_UNIT ) / ( CONVERT(DECIMAL(13, 4), CASE WHEN ISNULL(APRES_QT_CP,0)=0 THEN 1  ELSE APRES_QT_CP END) / 
																    CONVERT(DECIMAL(13, 4), CASE WHEN APRES_EMB_CP=0 THEN 1  ELSE APRES_EMB_CP END ) )), 4) 
										-
										  (	 SUM(d.VLR_ICMS_RET) / 
												ROUND(SUM(
													   D.QTDE_PROD * (  CONVERT(DECIMAL(13, 4), CASE WHEN ISNULL(APRES_QT_CP,0)=0 THEN 1  ELSE APRES_QT_CP END )
																				    /
																    CONVERT(DECIMAL(13, 4), CASE WHEN ISNULL(APRES_EMB_CP,0)=0 THEN 1  ELSE APRES_EMB_CP END ) 
																   )										  
												), 
											 4) 
										  ) AS VLR_IT--Abate Icms Retido

										,ROUND(SUM(D.QTDE_PROD * (  CONVERT(DECIMAL(13, 4),CASE WHEN ISNULL(APRES_QT_CP,0)=0 THEN 1  ELSE APRES_QT_CP END) /
															  CONVERT(DECIMAL(13, 4), CASE WHEN APRES_EMB_CP=0 THEN 1  ELSE APRES_EMB_CP END ) )), 4) QT_IT
										,ROUND(SUM(D.VLR_PROD_DESC), 4) VLR_PROD_DESC
									FROM
										#RS_ENT A
										INNER JOIN EST_NF_ENT_DANFE_PROVISORIO_ITENS D ON
											A.CD_CTR_DANFE = D.CD_CTR
									WHERE
										D.QTDE_PROD>0
									GROUP  BY
									 A.CD_EMP
									 ,A.CD_FILIAL
									 ,A.CD_CTR_DANFE
									 ,A.CD_PED
									 ,D.CD_PROD) D ON
				I.CD_EMP = D.CD_EMP AND
				I.CD_FILIAL = D.CD_FILIAL AND
				I.CD_PED = D.CD_PED AND
				I.CD_PROD = D.CD_PROD
				LEFT OUTER JOIN (
					SELECT CD_EMP, CD_FILIAL, CD_PED, CD_PROD, SUM(QT_PROD) AS QT_PROD
					FROM EST_PED_CP_IT_CANCEL_SLD 
					GROUP BY CD_EMP, CD_FILIAL, CD_PED, CD_PROD
				) AS C ON
					 I.CD_EMP = C.CD_EMP AND
					 I.CD_FILIAL = C.CD_FILIAL AND
					 I.CD_PED = C.CD_PED AND
					 I.CD_PROD = C.CD_PROD
		WHERE
			I.QT_IT     > 0 AND
			I.CD_EMP    = 1 AND
			I.CD_FILIAL = @CD_FILIAL

			 
		-- QTDE ITEM DIVERGENTE
		INSERT INTO #RS_BLOQ(CD_CTR,
								 TP_BLOQ,
								 CD_PED)
		SELECT DISTINCT
			A.CD_CTR_DANFE
			,7
			,A.CD_PED
		FROM
			#RS_ENT_IT A
			LEFT JOIN #RS_DANFE_LIB L ON
				A.CD_CTR_DANFE = L.CD_CTR AND
				L.TP_BLOQ = 7
		WHERE
			(QT_IT_DANFE > QT_IT_PED OR QT_IT_DANFE > QT_SALDO) AND
			L.CD_CTR IS NULL; --> QUE NAO ESTEJA LIBERADO..
			
			
		INSERT INTO #RS_BLOQ (CD_CTR,  TP_BLOQ, CD_PED)
		SELECT
			A.CD_CTR
			,7
			,A.CD_PED
		FROM
			(SELECT
				 A.CD_CTR
				 ,E.CD_PED
				 ,COUNT(DISTINCT CD_PROD) QT_SKU_DANFE
			 FROM
				 EST_NF_ENT_DANFE_PROVISORIO_ITENS A
				 JOIN #RS_ENT E ON
					 A.CD_CTR = E.CD_CTR_DANFE
			 GROUP  BY
				A.CD_CTR,E.CD_PED) a
			JOIN (SELECT
						e.CD_CTR_DANFE CD_CTR
						,A.CD_PED
						,COUNT(*)      QT_SKU_PED
					FROM
						EST_PED_CP_IT A
						JOIN #RS_ENT E ON
						A.CD_EMP = E.CD_EMP AND
						A.CD_PED = E.CD_PED AND
						A.CD_FILIAL = E.CD_FILIAL
					GROUP  BY
						e.CD_CTR_DANFE, A.CD_PED) b ON
			A.CD_CTR = B.CD_CTR AND
			A.QT_SKU_DANFE > B.QT_SKU_PED;

			
			
/**********************************************************************************************/
/**********************************************************************************************/
		--  VLR ITEM DIVERGENTE 
		--DECLARE @VLR_DIV MONEY =0.02
		INSERT INTO #RS_BLOQ
								(CD_CTR,
								 TP_BLOQ,
								 CD_PED)
		SELECT DISTINCT
			A.CD_CTR_DANFE
			,8
			,A.CD_PED
		FROM
			#RS_ENT_IT A
			LEFT JOIN #RS_DANFE_LIB L ON
				A.CD_CTR_DANFE = L.CD_CTR AND
				L.TP_BLOQ = 8
		WHERE
			( ( VLR_IT_DANFE - VLR_IT_DESC_DANFE ) - ( VLR_IT_PED - VLR_IT_DESC_PED ) ) > @VLR_DIV AND
			L.CD_CTR IS NULL; --> QUE NAO ESTEJA LIBERADO..


/**********************************************************************************************/
--Implementar uma forma melhor
    DECLARE @NaoUtilizaControleDivergenciaCompleto VARCHAR(MAX);

    SET @NaoUtilizaControleDivergenciaCompleto = ISNULL((SELECT valor FROM prc_emp_config WHERE cd_chave ='NAO_USA_CONTROLE_DIVERGENCIA_TOTAL'),'');

    IF @NaoUtilizaControleDivergenciaCompleto <> ''
    BEGIN
		BEGIN TRY
			DELETE FROM #RS_BLOQ WHERE TP_BLOQ IN (SELECT ID FROM DBO.UFD_PRM_IN_STRING(@NaoUtilizaControleDivergenciaCompleto))
		END TRY
		BEGIN CATCH
			PRINT 'ERRO AO CAPTURAR PARAMETRO DE EXCLUSAO'
		END CATCH
    END
/**********************************************************************************************/
		--Limpa itens duplicados
		INSERT INTO EST_NF_ENT_DANFE_PROVISORIO_BLOQUEIO_PENDENTE
								(CD_CTR,
								 CD_USU,
								 DT_CAD,
								 TIPO_BLQ,
								 CD_PED_COMPRA,
								 ORIGEM_BLOQUEIO)
		SELECT DISTINCT
			B.CD_CTR
			,1 CD_USU
			,GETDATE() DT_CAD
			,B.TP_BLOQ TIPO_BLQ
			,B.CD_PED  CD_PED_COMPRA
			,'P_EST_NF_ENT_DANFE_PROVISORIO_BLOQUEIO_PENDENTE'
		FROM
			#RS_BLOQ B
			LEFT JOIN EST_NF_ENT_DANFE_PROVISORIO_BLOQUEIO_PENDENTE W ON
				B.CD_CTR = W.CD_CTR AND
				B.TP_BLOQ = W.TIPO_BLQ
		WHERE
			W.CD_CTR IS NULL;

/**********************************************************************************************/
/**********************************************************************************************/
		--Remove bloqueio de vinculo..de pedido vinculado 
		DELETE FROM A
		FROM   
			EST_NF_ENT_DANFE_PROVISORIO_BLOQUEIO_PENDENTE A
			INNER JOIN EST_NF_ENT_DANFE_PROVISORIO_EST_PED_CP B ON
			A.CD_CTR = B.CD_CTR AND
			TIPO_BLQ IN( 0, 3 );

		--Remove bloqueio de danfes que ja entraram
		DELETE FROM A
		FROM   
			EST_NF_ENT_DANFE_PROVISORIO_BLOQUEIO_PENDENTE A
			INNER JOIN EST_NF_ENT_DANFE_PROVISORIO_EST_NF_ENT B ON
			A.CD_CTR = B.CD_CTR;    
			 
		--Remove bloqueio de danfes liberados
		DELETE FROM A
		FROM EST_NF_ENT_DANFE_PROVISORIO_BLOQUEIO_PENDENTE A
			 INNER JOIN EST_NF_ENT_DANFE_PROVISORIO B ON A.CD_CTR = B.CD_CTR
		WHERE
			 FLAG_LIBERA_ENTRADA_SEM_PEDIDO = 1;
		-- remove vinculo com pedido sem vinculo    
		DELETE V
		FROM
			EST_NF_ENT_DANFE_PROVISORIO_EST_PED_CP v INNER JOIN EST_NF_ENT_DANFE_PROVISORIO_PENDENTE pend ON
			v.CD_CTR = pend.CD_CTR
			INNER JOIN (
					select a.cd_emp,a.cd_ped,a.cd_filial	  			FROM 
						EST_PED_CP A
						LEFT JOIN EST_PED_CP_IT I ON		A.CD_EMP	= I.CD_EMP
													AND A.CD_PED	= I.CD_PED
													AND A.CD_FILIAL = I.CD_FILIAL
					WHERE 
						  I.CD_EMP IS NULL 
						AND A.CD_EMP = 1
						AND A.CD_FILIAL = @CD_FILIAL 
						AND NOT A.STS_PED = 2 )  i ON
			v.CD_EMP = i.CD_EMP AND
			v.CD_FILIAL = i.CD_FILIAL AND
			v.CD_PED = i.CD_PED
/**********************************************************************************************/
