IF EXISTS( SELECT * FROM SYS.PROCEDURES WHERE NAME = 'P_EST_PED_CP_LIMPA_PEDIDOS_VENCIDOS')
    BEGIN
        DROP PROCEDURE P_EST_PED_CP_LIMPA_PEDIDOS_VENCIDOS;
    END;
GO

--EXEC P_EST_PED_CP_LIMPA_PEDIDOS_VENCIDOS
CREATE PROCEDURE [DBO].[P_EST_PED_CP_LIMPA_PEDIDOS_VENCIDOS] @FLAG_CANCELAR_PENDENCIA_PARCIAL_IMEDIATO INT = 0
WITH ENCRYPTION
AS
SET DEADLOCK_PRIORITY 9
    BEGIN
		SET CONTEXT_INFO 0x99999 

        SET NOCOUNT ON;
        CREATE TABLE #RSPEDIDO_VENC
        (CD_EMP    INT,
         CD_FILIAL INT,
         CD_PED    INT,
         CD_PROD   INT,
         QT_PROD   MONEY
        );
        DECLARE @DIASVENCTO INT;
        DECLARE @QTDE_DIAS_CANCELAR_RESSUP INT;
        SET @DIASVENCTO = ISNULL(
                                (
                                    SELECT VALOR
                                    FROM PRC_EMP_CONFIG
                                    WHERE CD_CHAVE = 'QTDE_DIAS_VENCTO_CANCELAR_PENDENCIA_ENTRADA'
                                ), 15);
        PRINT @DIASVENCTO

        PRINT 'REMOVE DEMANDAS TEMPORARIAS ANTIGAS - Time ' + convert(varchar(20),getdate(),108);
        TRUNCATE TABLE EST_PROD_SUPRIMENTO_ENTREGA_LOJA;
        PRINT 'REMOVE GRUPO DE PEDIDOS SEM ITENS - Time ' + convert(varchar(20),getdate(),108);
        DELETE 
			EST_PED_ELTR_GRP_PED_EST_PED_ELTR
		FROM
		EST_PED_ELTR INNER JOIN EST_PED_ELTR_GRP_PED_EST_PED_ELTR ON
		EST_PED_ELTR.CD_EMP = EST_PED_ELTR_GRP_PED_EST_PED_ELTR.CD_EMP AND 
		EST_PED_ELTR.CD_PED_SOL= EST_PED_ELTR_GRP_PED_EST_PED_ELTR.CD_PED_SOL
		LEFT OUTER JOIN EST_PED_ELTR_IT IT ON
		EST_PED_ELTR.CD_EMP = IT.CD_EMP AND 
		EST_PED_ELTR.CD_PED_SOL = IT.CD_PED_SOL
		WHERE
			EST_PED_ELTR.CD_EMP =1
			AND EST_PED_ELTR.DT_PED >= GETDATE()-15
			AND IT.CD_PED_SOL IS NULL;

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

        PRINT 'CANCELANDO PEDIDO DE COMPRAS VENCIDO - Time ' + convert(varchar(20),getdate(),108);	 
        --CANCELANDO PEDIDO COM CODIGO FORNECEDOR ZERADO
        UPDATE EST_PED_CP
          SET
              STS_PED = 2,
              CD_USU_CANCEL = 1,
              DT_CANCEL = GETDATE(),
		    DT_ULT_ATU =GETDATE()
        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
             LEFT JOIN EST_NF_ENT_DANFE_PROVISORIO_EST_PED_CP
             ON EST_PED_CP.CD_EMP = EST_NF_ENT_DANFE_PROVISORIO_EST_PED_CP.CD_EMP
                AND EST_PED_CP.CD_FILIAL = EST_NF_ENT_DANFE_PROVISORIO_EST_PED_CP.CD_FILIAL
                AND EST_PED_CP.CD_PED = EST_NF_ENT_DANFE_PROVISORIO_EST_PED_CP.CD_PED
             LEFT JOIN EST_NF_ENT_PED_CP NPD
             ON EST_PED_CP.CD_EMP = NPD.CD_EMP
                AND EST_PED_CP.CD_FILIAL = NPD.CD_FILIAL
                AND EST_PED_CP.CD_PED = NPD.CD_PED
        WHERE EST_PED_CP.CD_EMP = 1
              AND NPD.CD_EMP IS NULL -- QUE NAO TENHA VINCULO COM NF --> CANCELAR NA ROTINA DE CANCEL SALDO
              AND DATEDIFF(DAY, EST_PED_CP.DT_PREV_ENT, GETDATE()) > @DIASVENCTO
              AND ISNULL(EST_PED_CP.CD_PED_FORN, '0') = '0'
              AND EST_PED_CP.CD_FILIAL NOT IN
        (
            SELECT CD_FILIAL
            FROM V_PRC_FILIAL_RELACAO_DEPOSITOS
        )
              AND EST_NF_ENT_DANFE_PROVISORIO_EST_PED_CP.CD_PED IS NULL;

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

        --FIM 
        PRINT 'CANCELANDO PEDIDOS ELETRONICOS VENCIDOS - Time ' + convert(varchar(20),getdate(),108);
        -- LIMPA OS PEDIDOS ELETRONICOS
        UPDATE EST_PED_ELTR
          SET
              FLAG_FECHAR = 1
        WHERE FLAG_FECHAR = 0
              AND DATEDIFF(DAY, DT_ENTR, GETDATE()) > @DIASVENCTO
              AND CD_EMP = 1;

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

		PRINT 'CANCELANDO PRE-FATURAS VENCIDAS - Time ' + convert(varchar(20),getdate(),108);
        UPDATE 
			EST_PED_VD
          SET
              EST_PED_VD.STS_PED = 2,
		    DT_ULT_ATU =GETDATE()
        FROM
			EST_PED_VD INNER JOIN EST_PED_VD_PENDENCIA ON
			EST_PED_VD.CD_EMP = EST_PED_VD_PENDENCIA.CD_EMP AND 
			EST_PED_VD.CD_FILIAL = EST_PED_VD_PENDENCIA.CD_FILIAL AND
			EST_PED_VD.CD_PED = EST_PED_VD_PENDENCIA.CD_PED 
		WHERE 
              EST_PED_VD.DT_VALID < CONVERT(CHAR(10),GETDATE(),112)
              AND EST_PED_VD.CD_EMP = 1;

        PRINT 'DELETANDO PENDENCIA DE COMPRAS VENCIDAS - Time ' + convert(varchar(20),getdate(),108);
        --DELETANDO PENDENCIA DE ENTRADA PEDIDO COM CODIGO FORNECEDOR ZERADO
        DELETE EST_PED_CP_PENDENCIA
        FROM EST_PED_CP
             LEFT JOIN EST_NF_ENT_DANFE_PROVISORIO_EST_PED_CP
             ON EST_PED_CP.CD_EMP = EST_NF_ENT_DANFE_PROVISORIO_EST_PED_CP.CD_EMP
                AND EST_PED_CP.CD_FILIAL = EST_NF_ENT_DANFE_PROVISORIO_EST_PED_CP.CD_FILIAL
                AND EST_PED_CP.CD_PED = EST_NF_ENT_DANFE_PROVISORIO_EST_PED_CP.CD_PED
             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
             LEFT JOIN EST_NF_ENT_PED_CP NPD
             ON EST_PED_CP.CD_EMP = NPD.CD_EMP
                AND EST_PED_CP.CD_FILIAL = NPD.CD_FILIAL
                AND EST_PED_CP.CD_PED = NPD.CD_PED
        WHERE EST_PED_CP.CD_EMP = 1
              AND NPD.CD_EMP IS NULL -- QUE NAO TENHA VINCULO COM NF --> CANCELAR NA ROTINA DE CANCEL SALDO
              AND DATEDIFF(DAY, EST_PED_CP.DT_PREV_ENT, GETDATE()) > @DIASVENCTO
              AND ISNULL(EST_PED_CP.CD_PED_FORN, '0') ='0'
              AND EST_PED_CP.CD_FILIAL NOT IN
        (
            SELECT CD_FILIAL
            FROM V_PRC_FILIAL_RELACAO_DEPOSITOS
        )
              AND EST_NF_ENT_DANFE_PROVISORIO_EST_PED_CP.CD_PED IS NULL;
        --FIM

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

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

        PRINT 'BAIXANDO PEDIDO DE COMPRAS COM XPED E NOTA DE ENTRADA - Time ' + convert(varchar(20),getdate(),108);
        --ALTERANDO PEDIDO DE COMPRAS COM XPED	
		CREATE TABLE #PedidoCompras (CD_EMP INT,
									 CD_FILIAL INT,
									 CD_PED INT,
									 CD_CTR INT)

		INSERT INTO #PedidoCompras(CD_EMP,CD_FILIAL,CD_PED,CD_CTR)		
		SELECT
			   EST_PED_CP.CD_EMP
			 , EST_PED_CP.CD_FILIAL
			 , EST_PED_CP.CD_PED
			 , EST_NF_ENT_DANFE_PROVISORIO_EST_PED_CP.CD_CTR
		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
			JOIN EST_NF_ENT_DANFE_PROVISORIO_EST_PED_CP ON EST_PED_CP.CD_EMP = EST_NF_ENT_DANFE_PROVISORIO_EST_PED_CP.CD_EMP
														   AND EST_PED_CP.CD_FILIAL = EST_NF_ENT_DANFE_PROVISORIO_EST_PED_CP.CD_FILIAL
														   AND EST_PED_CP.CD_PED = EST_NF_ENT_DANFE_PROVISORIO_EST_PED_CP.CD_PED
		WHERE  EST_PED_CP.CD_EMP = 1
			   AND DATEDIFF(DAY, EST_PED_CP.DT_PREV_ENT, GETDATE()) > @DIASVENCTO
			   AND EST_PED_CP.CD_FILIAL NOT IN(SELECT CD_FILIAL FROM V_PRC_FILIAL_RELACAO_DEPOSITOS);
		
		DELETE 
			P
		FROM 
			#PedidoCompras p INNER JOIN (SELECT
											EST_NF_ENT_DANFE_PROVISORIO_EST_PED_CP.CD_EMP,
											EST_NF_ENT_DANFE_PROVISORIO_EST_PED_CP.CD_FILIAL,
											EST_NF_ENT_DANFE_PROVISORIO_EST_PED_CP.CD_PED
										 FROM
											EST_NF_ENT_DANFE_PROVISORIO_EST_PED_CP INNER JOIN EST_NF_ENT_DANFE_PROVISORIO_PENDENTE ON
											EST_NF_ENT_DANFE_PROVISORIO_EST_PED_CP.CD_CTR = EST_NF_ENT_DANFE_PROVISORIO_PENDENTE.CD_CTR) rs on
			P.CD_EMP = rs.CD_EMP AND
			P.CD_FILIAL = rs.CD_FILIAL AND
			P.CD_PED = rs.CD_PED 

		UPDATE 
			EST_PED_CP
		 SET
			  STS_PED = 2
			, DT_ULT_ATU = CONVERT(CHAR(10), GETDATE(), 112)
			, DT_CANCEL = GETDATE()
			, CD_USU_CANCEL = 1
		FROM   EST_PED_CP INNER JOIN #PedidoCompras p ON 
			   EST_PED_CP.CD_EMP = p.CD_EMP AND 
			   EST_PED_CP.CD_FILIAL = p.CD_FILIAL AND 
			   EST_PED_CP.CD_PED = p.CD_PED
        /*************************************************************************************************************************************/

        PRINT 'DELETANDO PENDENCIA DE ENTRADA - Time ' + convert(varchar(20),getdate(),108);
        --DELETANDO PEDIDO DE COMPRAS COM XPED
        DELETE 
			EST_PED_CP_PENDENCIA
        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
			LEFT OUTER JOIN EST_NF_ENT_DANFE_PROVISORIO ON 
			EST_PED_CP.CD_EMP = EST_NF_ENT_DANFE_PROVISORIO.CD_EMP AND 
			EST_PED_CP.CD_FILIAL = EST_NF_ENT_DANFE_PROVISORIO.CD_FILIAL AND 
			EST_PED_CP.CD_PED_FORN = EST_NF_ENT_DANFE_PROVISORIO.CD_PED_FORN
			LEFT OUTER 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_PED_CP.CD_EMP = 1
            AND DATEDIFF(DAY, EST_PED_CP.DT_PREV_ENT, GETDATE()) > @DIASVENCTO
            AND EST_NF_ENT_DANFE_PROVISORIO_PENDENTE.CD_CTR IS NULL
            AND EST_PED_CP.CD_FILIAL NOT IN( SELECT CD_FILIAL FROM V_PRC_FILIAL_RELACAO_DEPOSITOS);

        --CANCELANDO RESSUPRIMENTOS NAO ATENDIDOS
        SET @QTDE_DIAS_CANCELAR_RESSUP = ISNULL((SELECT VALOR FROM PRC_EMP_CONFIG
                                                   WHERE CD_EMP = 1
                                                         AND CD_CHAVE = 'DIAS_PARA_CANCELAR_RESSUP_NAO_ATENDIDO'), 15);


        PRINT 'CANCELANDO RESSUPRIMENTO NAO ATENDIDOS - TIME ' + CONVERT(VARCHAR(20),GETDATE(),108);
		IF @QTDE_DIAS_CANCELAR_RESSUP > 0 
		BEGIN 
        UPDATE EST_PROD_TRANSF
          SET
              STS_TRANSF = 4,
              CD_USU = 1,
              DT_ULT_ATU = CONVERT( VARCHAR(10), GETDATE(), 112),
              OBSERVACAO = 'CANCELAMENTO EFETUADO POR MEIO AUTOMATICO'
        WHERE STS_TRANSF = 0
              AND DT_TRANSF < DATEADD(DAY, @QTDE_DIAS_CANCELAR_RESSUP * -1, CONVERT(VARCHAR(10), GETDATE(), 112));
        END 
		
		CREATE TABLE #TMP_DEL(CD_EMP     INT,CD_PED_SOL INT);

        INSERT INTO #TMP_DEL
               SELECT E.CD_EMP
                    , E.CD_PED_SOL
               FROM
                    EST_PED_ELTR E
                    LEFT OUTER JOIN EST_PED_ELTR_IT I
                    ON E.CD_EMP = I.CD_EMP
                       AND E.CD_PED_SOL = I.CD_PED_SOL
               WHERE I.CD_PED_SOL IS NULL
                     AND E.CD_EMP = 1
                     AND E.FLAG_FECHAR = 0
                     AND E.DT_PED > (GETDATE() - 5);

        PRINT 'EXCLUI EST_PED_ELTR_SUPRIMENTO_FABRIC - Time ' + convert(varchar(20),getdate(),108);
        DELETE 
			EST_PED_ELTR_SUPRIMENTO_FABRIC
        FROM 
			EST_PED_ELTR_SUPRIMENTO_FABRIC INNER JOIN #TMP_DEL D ON 
			EST_PED_ELTR_SUPRIMENTO_FABRIC.CD_EMP = D.CD_EMP AND 
			EST_PED_ELTR_SUPRIMENTO_FABRIC.CD_PED_SOL = D.CD_PED_SOL
        WHERE 
			EST_PED_ELTR_SUPRIMENTO_FABRIC.CD_EMP = 1;
        
		PRINT 'EXCLUI EST_PED_ELTR_SUPRIMENTO_IT_MESES - Time ' + convert(varchar(20),getdate(),108);
        DELETE 
			EST_PED_ELTR_SUPRIMENTO_IT_MESES
        FROM 
			EST_PED_ELTR_SUPRIMENTO_IT_MESES INNER JOIN #TMP_DEL D ON 
			EST_PED_ELTR_SUPRIMENTO_IT_MESES.CD_EMP = D.CD_EMP AND 
			EST_PED_ELTR_SUPRIMENTO_IT_MESES.CD_PED_SOL = D.CD_PED_SOL
        WHERE 
			EST_PED_ELTR_SUPRIMENTO_IT_MESES.CD_EMP = 1;
        
		PRINT 'EXCLUI EST_PED_ELTR_FORN_PED_CP - Time ' + convert(varchar(20),getdate(),108);
        DELETE 
			EST_PED_ELTR_FORN_PED_CP
        FROM 
			EST_PED_ELTR_FORN_PED_CP INNER JOIN #TMP_DEL D ON 
			EST_PED_ELTR_FORN_PED_CP.CD_EMP = D.CD_EMP AND 
			EST_PED_ELTR_FORN_PED_CP.CD_PED_SOL = D.CD_PED_SOL
        WHERE 
			EST_PED_ELTR_FORN_PED_CP.CD_EMP = 1;
        
		PRINT 'EXCLUI EST_PED_ELTR_ATIVA_CP_EST_PED_ELTR - Time ' + convert(varchar(20),getdate(),108);
        DELETE 
			EST_PED_ELTR_ATIVA_CP_EST_PED_ELTR
        FROM 
			EST_PED_ELTR_ATIVA_CP_EST_PED_ELTR INNER JOIN #TMP_DEL D ON 
			EST_PED_ELTR_ATIVA_CP_EST_PED_ELTR.CD_EMP = D.CD_EMP AND 
			EST_PED_ELTR_ATIVA_CP_EST_PED_ELTR.CD_PED_SOL = D.CD_PED_SOL
        WHERE 
			EST_PED_ELTR_ATIVA_CP_EST_PED_ELTR.CD_EMP = 1;
        
		DELETE 
			EST_PED_ELTR_UNI
        FROM 
			EST_PED_ELTR_UNI INNER JOIN #TMP_DEL D ON 
			EST_PED_ELTR_UNI.CD_EMP = D.CD_EMP AND 
			EST_PED_ELTR_UNI.CD_PED_SOL = D.CD_PED_SOL
        WHERE 
			EST_PED_ELTR_UNI.CD_EMP = 1;
        
		DELETE 
			FROM E
        FROM 
			EST_PED_ELTR_COT_COMPRA_EST_PED_ELTR E INNER JOIN #TMP_DEL D ON 
			E.CD_EMP = D.CD_EMP AND 
			E.CD_PED_SOL = D.CD_PED_SOL
        WHERE 
			E.CD_EMP = 1;
        
		PRINT 'EXCLUI EST_PED_ELTR_SUPRIMENTO_GRUPO - Time ' + convert(varchar(20),getdate(),108);
        DELETE 
			FROM 
				E
        FROM 
			EST_PED_ELTR_SUPRIMENTO_GRUPO E INNER JOIN #TMP_DEL D ON 
			E.CD_EMP = D.CD_EMP AND 
			E.CD_PED_SOL = D.CD_PED_SOL
        WHERE 
			E.CD_EMP = 1;
        
		PRINT 'EXCLUI EST_PED_ELTR - Time ' + convert(varchar(20),getdate(),108);
        DELETE 
			FROM 
				E
        FROM 
			EST_PROD_TRANSF_EST_PED_ELTR E INNER JOIN #TMP_DEL D ON 
			E.CD_EMP = D.CD_EMP AND 
			E.CD_PED_SOL = D.CD_PED_SOL
        WHERE 
			E.CD_EMP = 1;
        
		DELETE 
			FROM 
				E
        FROM 
			EST_PED_ELTR E INNER JOIN #TMP_DEL D ON 
			E.CD_EMP = D.CD_EMP AND 
			E.CD_PED_SOL = D.CD_PED_SOL
        WHERE 
			E.CD_EMP = 1;

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

        --EXCLUINDO PRE FATURAS SEM ITENS

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

        BEGIN TRY
            PRINT 'EXCLUI EST_NF_SAI_PED_VD - Time ' + convert(varchar(20),getdate(),108);
            --PRE-FATURA SEM ITENS
            DELETE   FROM   EST_NF_SAI_PED_VD 

			 FROM 
			     EST_NF_SAI_PED_VD
			     JOIN EST_PED_VD P ON 
			     EST_NF_SAI_PED_VD.CD_EMP = P.CD_EMP AND 
			     EST_NF_SAI_PED_VD.CD_FILIAL = P.CD_FILIAL AND 
			     EST_NF_SAI_PED_VD.CD_PED = P.CD_PED 
			     LEFT JOIN EST_PED_VD_IT ON 
			     EST_NF_SAI_PED_VD.CD_EMP = EST_PED_VD_IT.CD_EMP AND 
			     EST_NF_SAI_PED_VD.CD_FILIAL = EST_PED_VD_IT.CD_FILIAL AND 
			     EST_NF_SAI_PED_VD.CD_PED = EST_PED_VD_IT.CD_PED
			 WHERE 
			     P.CD_EMP = 1
			     AND P.DT_EMI_PED > GETDATE()-5
			     AND EST_PED_VD_IT.CD_PED IS NULL;
            
			PRINT 'EXCLUI EST_PED_VD_CONF_CPL - Time ' + convert(varchar(20),getdate(),108);
            --PRE-FATURA SEM ITENS
		DELETE FROM EST_PED_VD_CONF_CPL
	
            FROM EST_PED_VD_CONF_CPL
		          JOIN EST_PED_VD P ON 
			     EST_PED_VD_CONF_CPL.CD_EMP = P.CD_EMP AND 
			     EST_PED_VD_CONF_CPL.CD_FILIAL = P.CD_FILIAL AND 
			     EST_PED_VD_CONF_CPL.CD_PED = P.CD_PED 
                 LEFT OUTER JOIN EST_PED_VD_IT
                 ON EST_PED_VD_CONF_CPL.CD_EMP = EST_PED_VD_IT.CD_EMP
                    AND EST_PED_VD_CONF_CPL.CD_FILIAL = EST_PED_VD_IT.CD_FILIAL
                    AND EST_PED_VD_CONF_CPL.CD_PED = EST_PED_VD_IT.CD_PED
            WHERE EST_PED_VD_CONF_CPL.CD_EMP = 1
		        AND P.DT_EMI_PED > GETDATE()-5
                  AND EST_PED_VD_IT.CD_PED IS NULL;
            PRINT 'EXCLUI EST_PED_VD_CONF - Time ' + convert(varchar(20),getdate(),108);
            --PRE-FATURA SEM ITENS
            DELETE EST_PED_VD_CONF
            FROM EST_PED_VD_CONF
		       JOIN EST_PED_VD P ON 
			       EST_PED_VD_CONF.CD_EMP = P.CD_EMP AND 
			       EST_PED_VD_CONF.CD_FILIAL = P.CD_FILIAL AND 
			       EST_PED_VD_CONF.CD_PED = P.CD_PED 
                 LEFT OUTER JOIN EST_PED_VD_IT
                 ON EST_PED_VD_CONF.CD_EMP = EST_PED_VD_IT.CD_EMP
                    AND EST_PED_VD_CONF.CD_FILIAL = EST_PED_VD_IT.CD_FILIAL
                    AND EST_PED_VD_CONF.CD_PED = EST_PED_VD_IT.CD_PED
            WHERE EST_PED_VD_CONF.CD_EMP = 1
		        AND P.DT_EMI_PED > GETDATE()-5
                  AND EST_PED_VD_IT.CD_PED IS NULL;
            PRINT 'EXCLUI EST_NF_ENT_EST_PED_VD - Time ' + convert(varchar(20),getdate(),108);
            --PRE-FATURA SEM ITENS
            DELETE EST_NF_ENT_EST_PED_VD
            FROM EST_NF_ENT_EST_PED_VD
		       JOIN EST_PED_VD P ON 
			       EST_NF_ENT_EST_PED_VD.CD_EMP = P.CD_EMP AND 
			       EST_NF_ENT_EST_PED_VD.CD_FILIAL = P.CD_FILIAL AND 
			       EST_NF_ENT_EST_PED_VD.CD_PED = P.CD_PED 
                 LEFT OUTER JOIN EST_PED_VD_IT
                 ON EST_NF_ENT_EST_PED_VD.CD_EMP = EST_PED_VD_IT.CD_EMP
                    AND EST_NF_ENT_EST_PED_VD.CD_FILIAL = EST_PED_VD_IT.CD_FILIAL
                    AND EST_NF_ENT_EST_PED_VD.CD_PED = EST_PED_VD_IT.CD_PED
            WHERE EST_NF_ENT_EST_PED_VD.CD_EMP = 1
		        AND P.DT_EMI_PED > GETDATE()-5
                  AND EST_PED_VD_IT.CD_PED IS NULL;
            PRINT 'EXCLUI EST_PED_VD_ERROS_VALIDACAO - Time ' + convert(varchar(20),getdate(),108);
            --PRE-FATURA SEM ITENS	

            DELETE EST_PED_VD_ERROS_VALIDACAO
            FROM EST_PED_VD_ERROS_VALIDACAO
                 LEFT OUTER JOIN EST_PED_VD_IT
                 ON EST_PED_VD_ERROS_VALIDACAO.CD_EMP = EST_PED_VD_IT.CD_EMP
                    AND EST_PED_VD_ERROS_VALIDACAO.CD_FILIAL = EST_PED_VD_IT.CD_FILIAL
                    AND EST_PED_VD_ERROS_VALIDACAO.CD_PED = EST_PED_VD_IT.CD_PED
            WHERE EST_PED_VD_IT.CD_PED IS NULL;
            PRINT 'EXCLUI EST_PROD_TRANSF_PED_VD - Time ' + convert(varchar(20),getdate(),108);
            --PRE-FATURA SEM ITENS

            DELETE FROM H
		  
            FROM EST_PED_VD
                 INNER JOIN EST_PROD_TRANSF_PED_VD H
                 ON EST_PED_VD.CD_EMP = H.CD_EMP
                    AND EST_PED_VD.CD_FILIAL = H.CD_FILIAL
                    AND EST_PED_VD.CD_PED = H.CD_PED
                 LEFT OUTER JOIN EST_PED_VD_IT
                 ON EST_PED_VD.CD_EMP = EST_PED_VD_IT.CD_EMP
                    AND EST_PED_VD.CD_FILIAL = EST_PED_VD_IT.CD_FILIAL
                    AND EST_PED_VD.CD_PED = EST_PED_VD_IT.CD_PED
            WHERE
		         EST_PED_VD.DT_EMI_PED > GETDATE()-5 
		         AND EST_PED_VD_IT.CD_PED IS NULL;

            PRINT 'EXCLUI EST_PROD_REQ_TRANSF_LIB_EST_PED_VD - Time ' + convert(varchar(20),getdate(),108);
            --PRE-FATURA SEM ITENS
            DELETE FROM H
            FROM EST_PED_VD
                 INNER JOIN EST_PROD_REQ_TRANSF_LIB_EST_PED_VD H
                 ON EST_PED_VD.CD_EMP = H.CD_EMP
                    AND EST_PED_VD.CD_FILIAL = H.CD_FILIAL
                    AND EST_PED_VD.CD_PED = H.CD_PED
                 LEFT OUTER JOIN EST_PED_VD_IT
                 ON EST_PED_VD.CD_EMP = EST_PED_VD_IT.CD_EMP
                    AND EST_PED_VD.CD_FILIAL = EST_PED_VD_IT.CD_FILIAL
                    AND EST_PED_VD.CD_PED = EST_PED_VD_IT.CD_PED
            WHERE EST_PED_VD_IT.CD_PED IS NULL;
            DELETE FROM A
            FROM EST_PED_VD
                 INNER JOIN ADM_ERRO_EST_PED_VD A
                 ON EST_PED_VD.CD_EMP = A.CD_EMP
                    AND EST_PED_VD.CD_FILIAL = A.CD_FILIAL
                    AND EST_PED_VD.CD_PED = A.CD_PED
                 LEFT OUTER JOIN EST_PED_VD_IT
                 ON EST_PED_VD.CD_EMP = EST_PED_VD_IT.CD_EMP
                    AND EST_PED_VD.CD_FILIAL = EST_PED_VD_IT.CD_FILIAL
                    AND EST_PED_VD.CD_PED = EST_PED_VD_IT.CD_PED
            WHERE EST_PED_VD.DT_EMI_PED > GETDATE()-5 
		        AND EST_PED_VD_IT.CD_PED IS NULL;


            PRINT 'EXCLUI EST_PED_VD_GLB_MOV_OP_PRE_FATURA - Time ' + convert(varchar(20),getdate(),108);
            DELETE FROM A
            FROM EST_PED_VD
                 INNER JOIN EST_PED_VD_GLB_MOV_OP_PRE_FATURA A
                 ON EST_PED_VD.CD_EMP = A.CD_EMP
                    AND EST_PED_VD.CD_FILIAL = A.CD_FILIAL
                    AND EST_PED_VD.CD_PED = A.CD_PED
                 LEFT OUTER JOIN EST_PED_VD_IT
                 ON EST_PED_VD.CD_EMP = EST_PED_VD_IT.CD_EMP
                    AND EST_PED_VD.CD_FILIAL = EST_PED_VD_IT.CD_FILIAL
                    AND EST_PED_VD.CD_PED = EST_PED_VD_IT.CD_PED
            WHERE EST_PED_VD.DT_EMI_PED > GETDATE()-5
		        AND EST_PED_VD_IT.CD_PED IS NULL;



            PRINT 'EXCLUI EST_PED_VD - Time ' + convert(varchar(20),getdate(),108);
            DELETE FROM  EST_PED_VD
		 
            FROM EST_PED_VD
                 LEFT OUTER JOIN EST_PED_VD_IT
                 ON EST_PED_VD.CD_EMP = EST_PED_VD_IT.CD_EMP
                    AND EST_PED_VD.CD_FILIAL = EST_PED_VD_IT.CD_FILIAL
                    AND EST_PED_VD.CD_PED = EST_PED_VD_IT.CD_PED
            WHERE EST_PED_VD.DT_EMI_PED > GETDATE()-5 
		        AND EST_PED_VD_IT.CD_PED IS NULL;
        END TRY
        BEGIN CATCH
            PRINT 'FALHA AO EXCLUIR PREFATURAS SEM ITENS - Time ' + convert(varchar(20),getdate(),108);
        END CATCH;

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

        --CANCELAMENTO DE NOTAS FISCAIS COM PENDENCIA CANCELADA

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


        BEGIN TRY
            PRINT 'EXCLUI EST_NF_SAI_PENDENCIA - Time ' + convert(varchar(20),getdate(),108);
            DELETE EST_NF_SAI_PENDENCIA
            FROM EST_NF_SAI_PENDENCIA
                 INNER JOIN EST_NF_SAI
                 ON EST_NF_SAI_PENDENCIA.CD_EMP = EST_NF_SAI.CD_EMP
                    AND EST_NF_SAI_PENDENCIA.CD_FILIAL = EST_NF_SAI.CD_FILIAL
                    AND EST_NF_SAI_PENDENCIA.CD_NF = EST_NF_SAI.CD_NF
            WHERE EST_NF_SAI.CD_EMP = 1
                  AND PEND_ENTRADA = 1;
        END TRY
        BEGIN CATCH
            PRINT 'FALHA AO EXCLUIR EST_NF_SAI_PENDENCIA - Time ' + convert(varchar(20),getdate(),108);
        END CATCH;
        PRINT 'EXCLUI EST_PED_ELTR - Time ' + convert(varchar(20),getdate(),108);
        UPDATE E
          SET
              E.FLAG_FECHAR = 1,
			  E.HIST_CANCEL='FECHAMENTO DE DEMANDA POR DATA DE VENCIMENTO, CONFIGURADO PARA CANCELAR EM ' + CONVERT(VARCHAR(10),@DIASVENCTO) + ' DIAS.'
        FROM EST_PED_ELTR E
        WHERE E.CD_EMP = 1
              AND NOT E.STS_PED IN(3, 4)
        AND E.FLAG_FECHAR = 0
        AND DATEDIFF(DAY, E.DT_PED, GETDATE()) > @DIASVENCTO;

        --RETIRANDO PRODUTO INATIVO COM SOLICITACAO DE TRANSFERENCIA
        DELETE EST_PROD_REQ_TRANSF_SLD
        FROM EST_PROD_REQ_TRANSF_SLD
             INNER JOIN EST_PROD
             ON EST_PROD_REQ_TRANSF_SLD.CD_EMP = EST_PROD.CD_EMP
                AND EST_PROD_REQ_TRANSF_SLD.CD_PROD = EST_PROD.CD_PROD
             INNER JOIN EST_PROD_CPL
             ON EST_PROD_REQ_TRANSF_SLD.CD_EMP = EST_PROD_CPL.CD_EMP
                AND EST_PROD_REQ_TRANSF_SLD.CD_FILIAL_ORIG_PROD = EST_PROD_CPL.CD_FILIAL
                AND EST_PROD_REQ_TRANSF_SLD.CD_PROD = EST_PROD_CPL.CD_PROD
        WHERE EST_PROD_CPL.STS_PROD = 1
              OR EST_PROD.STS_PROD = 1;


		IF @QTDE_DIAS_CANCELAR_RESSUP > 0 
		begin 
        PRINT 'CANCELANDO RESSUPRIMENTO SEM ITENS - Time ' + convert(varchar(20),getdate(),108);
        UPDATE EST_PROD_TRANSF
          SET
              EST_PROD_TRANSF.STS_TRANSF = 4,
              EST_PROD_TRANSF.CD_USU = 1,
              EST_PROD_TRANSF.DT_ULT_ATU = CONVERT( VARCHAR(10), GETDATE(), 112),
              EST_PROD_TRANSF.OBSERVACAO = 'RESSUPRIMENTO SEM ITENS' 
        FROM EST_PROD_TRANSF
             LEFT OUTER JOIN EST_PROD_TRANSF_IT
             ON EST_PROD_TRANSF.CD_EMP = EST_PROD_TRANSF_IT.CD_EMP
                AND EST_PROD_TRANSF.CD_FILIAL = EST_PROD_TRANSF_IT.CD_FILIAL
                AND EST_PROD_TRANSF.CD_CTR = EST_PROD_TRANSF_IT.CD_CTR
        WHERE EST_PROD_TRANSF.DT_TRANSF < DATEADD(DAY, @QTDE_DIAS_CANCELAR_RESSUP * -1, CONVERT(VARCHAR(10), GETDATE(), 112))
              AND EST_PROD_TRANSF_IT.CD_CTR IS NULL;
		END 
        PRINT 'VINCULO NOTA FISCAL DE ENTRADA COM A PRE-ENTRADA - Time ' + convert(varchar(20),getdate(),108);

        INSERT INTO EST_NF_ENT_PRE_ENTRADA_EST_NF_ENT
               SELECT DE.CD_EMP
                    , DE.CD_FILIAL
                    , DE.CD_NF
                    , EC.CD_CTR_PRE_ENTRADA
               FROM
                    EST_NF_ENT_PRE_ENTRADA EC
                    INNER JOIN EST_NF_ENT_DANFE_PROVISORIO_EST_NF_ENT_PRE_ENTRADA D
                    ON EC.CD_EMP = D.CD_EMP
                       AND EC.CD_CTR_PRE_ENTRADA = D.CD_CTR_PRE_ENTRADA
                    INNER JOIN EST_NF_ENT_DANFE_PROVISORIO_EST_NF_ENT DE
                    ON D.CD_CTR = DE.CD_CTR
                    LEFT OUTER JOIN EST_NF_ENT_PRE_ENTRADA_EST_NF_ENT E
                    ON DE.CD_EMP = E.CD_EMP
                       AND DE.CD_FILIAL = E.CD_FILIAL
                       AND DE.CD_NF = E.CD_NF
               WHERE E.CD_NF IS NULL
			 

        PRINT 'VINCULO PEDIDO DE COMPRAS COM A PRE-ENTRADA - Time ' + convert(varchar(20),getdate(),108);
        INSERT INTO EST_NF_ENT_PED_CP(CD_EMP, CD_FILIAL, CD_PED, CD_NF, DT_CAD)
        SELECT DISTINCT
		    EC.CD_EMP
            , EC.CD_FILIAL
            , EC.CD_PED
            , DE.CD_NF
            , GETDATE()
        FROM
			EST_NF_ENT_PRE_ENTRADA EC
			JOIN EST_PED_CP P ON 
			EC.CD_EMP =P.CD_EMP  AND
			EC.CD_PED =P.CD_PED AND
			EC.CD_FILIAL =P.CD_FILIAL 

			INNER JOIN EST_NF_ENT_DANFE_PROVISORIO_EST_NF_ENT_PRE_ENTRADA D ON 
			EC.CD_EMP = D.CD_EMP AND 
			EC.CD_CTR_PRE_ENTRADA = D.CD_CTR_PRE_ENTRADA

			INNER JOIN EST_NF_ENT_DANFE_PROVISORIO_EST_NF_ENT DE ON 
			D.CD_CTR = DE.CD_CTR AND 
			EC.CD_FILIAL = DE.CD_FILIAL

			LEFT OUTER JOIN EST_NF_ENT_PED_CP E ON 
			EC.CD_EMP = E.CD_EMP AND 
			EC.CD_FILIAL = E.CD_FILIAL AND 
			DE.CD_NF = E.CD_NF
		WHERE E.CD_NF IS NULL;

			
        PRINT 'ERROS DE IMPORTACAO DE DANFE PROVISORIO - Time ' + convert(varchar(20),getdate(),108);
        UPDATE R
          SET
              R.STS_IMPORT = 5
        FROM NFE..EST_NF_NFE_RECEBIMENTO R
             INNER JOIN EST_NF_ENT_DANFE_PROVISORIO E
             ON R.CHAVE_NFE COLLATE SQL_LATIN1_GENERAL_CP1_CI_AS = E.NR_AUTORIZADOR
        WHERE 
              R.STS_IMPORT IN (2,3);
        
		UPDATE R
          SET
              R.STS_IMPORT = 5
        FROM NFE..EST_NF_NFE_RECEBIMENTO R
        WHERE R.DH_IMPORT <= (GETDATE() - 20)
              AND R.STS_IMPORT IN (2,3);

        PRINT 'DANFE NAO ENCONTRADO - Time ' + convert(varchar(20),getdate(),108);
        DELETE EST_NF_ENT_DANFE_PROVISORIO_NAO_ENCONTRADO
        FROM EST_NF_ENT_DANFE_PROVISORIO
             INNER JOIN EST_NF_ENT_DANFE_PROVISORIO_NAO_ENCONTRADO
             ON EST_NF_ENT_DANFE_PROVISORIO.NR_AUTORIZADOR = EST_NF_ENT_DANFE_PROVISORIO_NAO_ENCONTRADO.NR_AUTORIZADOR;
        
		DELETE EST_NF_ENT_DANFE_PROVISORIO_DOWNLOAD
        FROM EST_NF_ENT_DANFE_PROVISORIO
             INNER JOIN EST_NF_ENT_DANFE_PROVISORIO_DOWNLOAD
             ON EST_NF_ENT_DANFE_PROVISORIO.NR_AUTORIZADOR = EST_NF_ENT_DANFE_PROVISORIO_DOWNLOAD.NR_AUTORIZADOR;

		UPDATE
			EST_NF_NFE_RECEBIMENTO
		SET 
			 EST_NF_NFE_RECEBIMENTO.CD_FILIAL=EST_NF_ENT_DANFE_PROVISORIO.CD_FILIAL
		FROM
			EST_NF_NFE_RECEBIMENTO INNER JOIN EST_NF_ENT_DANFE_PROVISORIO ON
			EST_NF_NFE_RECEBIMENTO.CHAVE_NFE = EST_NF_ENT_DANFE_PROVISORIO.NR_AUTORIZADOR AND 
			EST_NF_NFE_RECEBIMENTO.CD_FILIAL <> EST_NF_ENT_DANFE_PROVISORIO.CD_FILIAL
		WHERE
			EST_NF_NFE_RECEBIMENTO.DH_IMPORT >= GETDATE()-20
	
        DELETE FROM EST_NF_ENT_DANFE_PROVISORIO_NAO_ENCONTRADO
        WHERE DT_CAD <= (GETDATE() - 20);
        PRINT 'PENDENCIA DE ENVIO WMS - Time ' + convert(varchar(20),getdate(),108);
        DELETE EST_WMS_ENT_RET_PEND
        FROM EST_NF_SAI_EST_WMS_ENT
             LEFT OUTER JOIN EST_NF_SAI_PENDENCIA
             ON EST_NF_SAI_EST_WMS_ENT.CD_EMP = EST_NF_SAI_PENDENCIA.CD_EMP
                AND EST_NF_SAI_EST_WMS_ENT.CD_FILIAL_ORIG = EST_NF_SAI_PENDENCIA.CD_FILIAL
                AND EST_NF_SAI_EST_WMS_ENT.CD_NF_ORIG = EST_NF_SAI_PENDENCIA.CD_NF
             INNER JOIN EST_WMS_ENT_RET_PEND
             ON EST_NF_SAI_EST_WMS_ENT.CD_PED_WMS = EST_WMS_ENT_RET_PEND.CD_PED_WMS
        WHERE EST_NF_SAI_PENDENCIA.CD_EMP IS NULL;

        /****************************************************************************************************************************/
        --ROTINA DE CANCELAMENTO DE PEDIDO PARCIAL
        /********************************************************************************************************************************/

        --CANCELAR PEDIDO PARCIAL IMEDIATO

		--SE O @FLAG_CANCELAR_PENDENCIA_PARCIAL_IMEDIATO = 1, CANCELA TODO O SALDO DO PEDIDO, MESMO QUE O PRODUTO NAO ESTEJA NO XML

		--SE O @FLAG_CANCELAR_PENDENCIA_PARCIAL_IMEDIATO = 2, CANCELA O SALDO DO PEDIDO, MAS SOMENTE DOS PRODUTOS QUE VIERAM A MENOR NO XML. 
		--OS PRODUTOS QUE, POR VENTURA, NAO VIERAM NO XML, CONTINUAM COM SALDO PENDENTE
        IF @FLAG_CANCELAR_PENDENCIA_PARCIAL_IMEDIATO = 1
            BEGIN
                SET @DIASVENCTO = 0;


				PRINT 'RETIRANDO PEDIDO DE COMPRAS COM ENTREGA PARCIAL VENCIDOS '+CONVERT(VARCHAR(8), @DIASVENCTO) + ' - Time ' + convert(varchar(20),getdate(),108);
				--RETIRANDO PEDIDO COM ENTREGA PARCIAL
				INSERT INTO #RSPEDIDO_VENC(CD_EMP, CD_FILIAL, CD_PED, CD_PROD, QT_PROD)
					   SELECT DISTINCT
							  EST_PED_CP_IT.CD_EMP
							, EST_PED_CP_IT.CD_FILIAL
							, EST_PED_CP_IT.CD_PED
							, EST_PED_CP_IT.CD_PROD
							, EST_PED_CP_IT.QT_IT_SLD - COALESCE(DP.QT_IT, 0) AS QT_IT
					   FROM
							EST_PED_CP_IT 
							INNER JOIN EST_PED_CP ON 
								EST_PED_CP_IT.CD_EMP = EST_PED_CP.CD_EMP AND 
								EST_PED_CP_IT.CD_FILIAL = EST_PED_CP.CD_FILIAL AND 
								EST_PED_CP_IT.CD_PED = EST_PED_CP.CD_PED
							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 --Q NAO TENHA VINCULO COM DANFE PENDENTE
							JOIN(SELECT
											  I.CD_EMP
											, I.CD_PED
											, I.CD_FILIAL
											, I.CD_PROD
											, SUM(W.QTDE_PROD * W.APRES_EMB_CP * W.APRES_QT_CP) AS QT_IT
										FROM
											EST_NF_ENT_DANFE_PROVISORIO_EST_PED_CP 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 = I.CD_PED
											INNER JOIN EST_PED_CP P ON 
												V.CD_EMP = P.CD_EMP
												AND V.CD_FILIAL = P.CD_FILIAL
												AND V.CD_PED = P.CD_PED
											INNER JOIN EST_NF_ENT_DANFE_PROVISORIO_PENDENTE PEND ON
												V.CD_CTR = PEND.CD_CTR
											INNER JOIN EST_NF_ENT_DANFE_PROVISORIO_ITENS W ON
												V.CD_EMP = W.CD_EMP
												AND V.CD_CTR = W.CD_CTR
												AND I.CD_PROD = W.CD_PROD
										GROUP BY
											I.CD_EMP
											, I.CD_PED
											, I.CD_FILIAL
											, I.CD_PROD ) DP ON 
								EST_PED_CP_IT.CD_EMP		= DP.CD_EMP
								AND EST_PED_CP_IT.CD_FILIAL = DP.CD_FILIAL
								AND EST_PED_CP_IT.CD_PED	= DP.CD_PED
								AND EST_PED_CP_IT.CD_PROD	= DP.CD_PROD
					   WHERE
							EST_PED_CP_IT.CD_EMP = 1
							AND EST_PED_CP_IT.QT_IT_SLD > 0
							AND EST_PED_CP.STS_PED <> 2 -- Q AINDA NAO FOI CANCELADO
							AND DATEDIFF(DAY, EST_PED_CP.DT_PREV_ENT, GETDATE()) > @DIASVENCTO
							AND EST_PED_CP_IT.QT_IT_SLD > COALESCE(DP.QT_IT, 0)
							AND EST_PED_CP.CD_FILIAL NOT IN (SELECT CD_FILIAL FROM V_PRC_FILIAL_RELACAO_DEPOSITOS) 
					   ORDER BY CD_PED;


				--Remove quem nao é eletronico
				delete from c
					FROM 
						#RSPEDIDO_VENC  c
						join EST_PED_ELTR_FORN_PED_CP e on 
						c.cd_emp = e.cd_emp and
						c.cd_filial = e.cd_fil_entr and
						c.cd_ped = e.cd_ped
						join EST_PED_ELTR w on 
						e.cd_emp		= w.cd_emp and
						e.cd_fil_entr 	= w.cd_filial and
						e.cd_ped_Sol	= w.cd_ped_sol
					WHERE  w.tp_req> 0;

            END;


		IF @FLAG_CANCELAR_PENDENCIA_PARCIAL_IMEDIATO = 2
            BEGIN
                SET @DIASVENCTO = 0;

				PRINT 'RETIRANDO OS PRODUTOS DOS PEDIDOS DE COMPRAS COM ENTREGA PARCIAL VENCIDOS '+CONVERT(VARCHAR(8), @DIASVENCTO) + ' - Time ' + convert(varchar(20),getdate(),108);
				--RETIRANDO PEDIDO COM ENTREGA PARCIAL
				INSERT INTO #RSPEDIDO_VENC(CD_EMP , CD_FILIAL , CD_PED , CD_PROD , QT_PROD)
					   SELECT DISTINCT
							  EST_PED_CP_IT.CD_EMP
							, EST_PED_CP_IT.CD_FILIAL
							, EST_PED_CP_IT.CD_PED
							, EST_PED_CP_IT.CD_PROD
							, EST_PED_CP_IT.QT_IT_SLD - DP.QT_IT AS QT_IT
					   FROM
							EST_PED_CP_IT 
							INNER JOIN EST_PED_CP ON 
								EST_PED_CP_IT.CD_EMP = EST_PED_CP.CD_EMP AND 
								EST_PED_CP_IT.CD_FILIAL = EST_PED_CP.CD_FILIAL AND 
								EST_PED_CP_IT.CD_PED = EST_PED_CP.CD_PED
							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 --Q NAO TENHA VINCULO COM DANFE PENDENTE
							INNER JOIN
					   (
						   SELECT
								  I.CD_EMP
								, I.CD_PED
								, I.CD_FILIAL
								, I.CD_PROD
								, SUM(W.QTDE_PROD * W.APRES_EMB_CP * W.APRES_QT_CP) AS QT_IT
						   FROM
								EST_NF_ENT_DANFE_PROVISORIO_EST_PED_CP 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 = I.CD_PED
								INNER JOIN EST_PED_CP P ON 
									V.CD_EMP = P.CD_EMP
									AND V.CD_FILIAL = P.CD_FILIAL
									AND V.CD_PED = P.CD_PED
								INNER JOIN EST_NF_ENT_DANFE_PROVISORIO_PENDENTE PEND ON
									V.CD_CTR = PEND.CD_CTR
								INNER JOIN EST_NF_ENT_DANFE_PROVISORIO_ITENS W ON
									V.CD_EMP = W.CD_EMP
									AND V.CD_CTR = W.CD_CTR
									AND I.CD_PROD = W.CD_PROD
							GROUP BY
								I.CD_EMP
								, I.CD_PED
								, I.CD_FILIAL
								, I.CD_PROD
					   ) DP ON 
							EST_PED_CP_IT.CD_EMP = DP.CD_EMP
							AND EST_PED_CP_IT.CD_FILIAL = DP.CD_FILIAL
							AND EST_PED_CP_IT.CD_PED = DP.CD_PED
							AND EST_PED_CP_IT.CD_PROD = DP.CD_PROD
					   WHERE
							EST_PED_CP_IT.CD_EMP = 1
							AND EST_PED_CP_IT.QT_IT_SLD > 0
							AND EST_PED_CP.STS_PED <> 2 -- Q AINDA NAO FOI CANCELADO
							AND DATEDIFF(DAY, EST_PED_CP.DT_PREV_ENT, GETDATE()) > @DIASVENCTO
							AND EST_PED_CP_IT.QT_IT_SLD > DP.QT_IT
							AND EST_PED_CP.CD_FILIAL NOT IN (SELECT CD_FILIAL FROM V_PRC_FILIAL_RELACAO_DEPOSITOS)
                     
					   ORDER BY CD_PED;
            END;
        
		

        /****************************************************************************************************************************/
        --CANCELAMENTO DE SALDO
        /****************************************************************************************************************************/

        PRINT 'REALIZANDO O CANCELAMENTO DO SALDO - Time ' + convert(varchar(20),getdate(),108);
        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
            , 1
            , V.QT_PROD
            , convert(date, GETDATE()) 
			, 'P_EST_PED_CP_LIMPA_PEDIDOS_VENCIDOS'
			, GETDATE()
        FROM
            #RSPEDIDO_VENC V
            LEFT JOIN EST_PED_CP_IT_CANCEL_SLD C ON 
				V.CD_EMP = C.CD_EMP
				AND V.CD_FILIAL = C.CD_FILIAL
				AND V.CD_PED	= C.CD_PED
				AND V.CD_PROD	= C.CD_PROD

			--LEFT JOIN ( SELECT 
			--			V.CD_EMP	,
			--			V.CD_FILIAL ,
			--			V.CD_PED
			--			fROM 
			--			EST_NF_ENT_DANFE_PROVISORIO_EST_PED_CP v  
			--			JOIN EST_NF_ENT_DANFE_PROVISORIO_PENDENTE pend on 
			--			v.CD_CTR = pend.CD_CTR
			--			) pend ON
			--		V.CD_EMP	= pend.CD_EMP
			--	AND V.CD_FILIAL = pend.CD_FILIAL
			--	AND V.CD_PED	= pend.CD_PED
        WHERE 
			V.QT_PROD > 0
            AND C.CD_EMP IS NULL
			--AND pend.CD_PED IS NULL
			;

	
        /********************************************************************************************************************************/
		PRINT 'DELETANDO PENDENCIA PEDIDO COMPRAS VENCIDO - Time ' + convert(varchar(20),getdate(),108);
        DELETE EST_PED_CP_PENDENCIA
        FROM #RSPEDIDO_VENC P
             INNER JOIN EST_PED_CP_PENDENCIA
             ON P.CD_EMP = EST_PED_CP_PENDENCIA.CD_EMP
                AND P.CD_FILIAL = EST_PED_CP_PENDENCIA.CD_FILIAL
                AND P.CD_PED = EST_PED_CP_PENDENCIA.CD_PED; 
        /****************************************************************************************************************************/

		PRINT 'DELETANDO PENDENCIA DANFE BLOQUEADO JA LIBERADO PELO TIPO - Time ' + convert(varchar(20),getdate(),108);
		DELETE P
        FROM EST_NF_ENT_DANFE_PROVISORIO_LIBERACAO_TIPO_BLQ L
             INNER JOIN EST_NF_ENT_DANFE_PROVISORIO_BLOQUEIO_PENDENTE P
             ON L.CD_CTR = P.CD_CTR
                AND L.TIPO_BLQ = P.TIPO_BLQ;	

        --CORRIGIDNO A FORN VALID COM VINCULO ERRADO
		PRINT 'ANALISANDO DANFE VALIDACAO COM NUMERACAO DE NOTA FISCAL ERRADA (EST_NF_ENT_EST_NF_ENT_NFE_FORN_VALID) - Time ' + convert(varchar(20),getdate(),108);
        DELETE 
			VENT  FROM 
			EST_NF_ENT_EST_NF_ENT_NFE_FORN_VALID VENT 
				INNER JOIN EST_NF_ENT_NFE_FORN_VALID V
             ON VENT.CD_CTR = V.CD_CTR
        WHERE 
			ISNUMERIC(SUBSTRING(V.NR_AUTORIZADOR, 26, 9)) =1 
			AND CONVERT(INT, SUBSTRING(V.NR_AUTORIZADOR, 26, 9), 9) <> V.NR_NF
			AND V.DT_CAD >=GETDATE()-15;
		
		PRINT 'DELETANDO DANFE VALIDACAO COM NUMERACAO DE NOTA FISCAL ERRADA (EST_NF_ENT_EST_NF_ENT_NFE_FORN_VALID) - Time ' + convert(varchar(20),getdate(),108);
		DELETE 
			FROM 
			EST_NF_ENT_NFE_FORN_VALID
        WHERE 
			ISNUMERIC(SUBSTRING(NR_AUTORIZADOR, 26, 9)) =1 
			AND
			CONVERT(INT, SUBSTRING(NR_AUTORIZADOR, 26, 9), 9) <> NR_NF
			AND DT_CAD >=GETDATE()-15;

        --DANFE COM LIBERACAO SEM VINCULO COM O PEDIDO
        INSERT INTO EST_NF_ENT_DANFE_PROVISORIO_EST_PED_CP
                (
                   CD_CTR
                  ,CD_EMP
                  ,CD_FILIAL
                  ,CD_PED
                  ,CD_USU
                  ,DT_CAD
                )
               SELECT DISTINCT
                      L.CD_CTR
                    , P.CD_EMP
                    , P.CD_FILIAL
                    , L.CD_PED_COMPRA
                    , L.CD_USU_LIB
                    , GETDATE()
               FROM
                    EST_NF_ENT_DANFE_PROVISORIO_LIBERACAO L
                    INNER JOIN EST_NF_ENT_DANFE_PROVISORIO P
                    ON L.CD_CTR = P.CD_CTR
                    INNER JOIN EST_NF_ENT_DANFE_PROVISORIO_PENDENTE PEND
                    ON L.CD_CTR = PEND.CD_CTR
                    LEFT OUTER JOIN EST_NF_ENT_DANFE_PROVISORIO_EST_PED_CP PED
                    ON L.CD_CTR = PED.CD_CTR
               WHERE L.TIPO_BLQ = 2
                     AND PED.CD_CTR IS NULL
                     AND L.CD_PED_COMPRA > 0;

        --DELETAR PENDENCIA DE PROCESSAMENTO IMPOSTO COM VALIDACAO JA REALIZADA.
        DELETE EST_NF_ENT_DANFE_PROVISORIO_ITENS_VALIDACAO_IMPOSTO_PENDENTE
        FROM EST_NF_ENT_DANFE_PROVISORIO_ITENS_VALIDACAO_IMPOSTO
             INNER JOIN EST_NF_ENT_DANFE_PROVISORIO_ITENS_VALIDACAO_IMPOSTO_PENDENTE
             ON EST_NF_ENT_DANFE_PROVISORIO_ITENS_VALIDACAO_IMPOSTO.CD_CTR = EST_NF_ENT_DANFE_PROVISORIO_ITENS_VALIDACAO_IMPOSTO_PENDENTE.CD_CTR
                AND EST_NF_ENT_DANFE_PROVISORIO_ITENS_VALIDACAO_IMPOSTO.CD_CTR_IT = EST_NF_ENT_DANFE_PROVISORIO_ITENS_VALIDACAO_IMPOSTO_PENDENTE.CD_CTR_IT;

        --DELETANDO NOTA FISCAL PENDENTE DE VALIDACAO 
        --JA VALIDADA.
        DELETE EST_NF_ENT_NFE_FORN_VALID_PENDENTE
        FROM EST_NF_ENT_NFE_FORN_VALID
             INNER JOIN EST_NF_ENT_NFE_FORN_VALID_PENDENTE
             ON EST_NF_ENT_NFE_FORN_VALID.CD_CTR = EST_NF_ENT_NFE_FORN_VALID_PENDENTE.CD_CTR
        WHERE EST_NF_ENT_NFE_FORN_VALID.VALIDACAO IN (1,4);

        --TRATAMENTO DE ERRO DE VALIDACAO DE NOTA FISCAL FORNECEDOR
        --PROCESSO SUBSTITUIDO PELO MANIFESTO DE NOTA FISCAL
        --CASO TENHA ERRO ESTE IRA CORRIGIR
        UPDATE 
			V
        SET
              V.DT_EMI_NF = D.DT_EMIS_NF
        FROM 
			EST_NF_ENT_DANFE_PROVISORIO D INNER JOIN EST_NF_ENT_NFE_FORN_VALID V ON 
			D.CD_EMP = V.CD_EMP AND 
			D.CD_FILIAL = V.CD_FILIAL AND 
			D.CD_FORN = V.CD_FORN AND 
			D.NR_NF = V.NR_NF AND 
			D.DT_EMIS_NF <> V.DT_EMI_NF
            INNER JOIN EST_NF_ENT_DANFE_PROVISORIO_ERROS_VALIDACAO ER ON 
			D.CD_CTR = ER.CD_CTR;

        PRINT 'CORRIGINDO VALIDACAO FORNECEDOR QUANDO O DANFE ESTIVER OK - Time ' + convert(varchar(20),getdate(),108);
		UPDATE 
			V
        SET
              VALIDACAO = 4,
			  DT_VALIDACAO=GETDATE()
        FROM 
			EST_NF_ENT_NFE_FORN_VALID_PENDENTE INNER JOIN EST_NF_ENT_NFE_FORN_VALID v ON
			EST_NF_ENT_NFE_FORN_VALID_PENDENTE.CD_CTR = v.CD_CTR
		WHERE 
			v.VALIDACAO IN(0,2,7);
		
        
		PRINT 'DELETANDO PEDIDO DE COMPRAS SEM ITENS COM VINCULO COM FORNECEDOR VINCULADO - Time ' + convert(varchar(20),getdate(),108);
        DELETE 
			EST_PED_CP_PED_CP_FORN_VINCULADO
        FROM 
			EST_PED_CP_PED_CP_FORN_VINCULADO LEFT OUTER JOIN EST_PED_CP_IT ON 
			EST_PED_CP_PED_CP_FORN_VINCULADO.CD_EMP = EST_PED_CP_IT.CD_EMP AND 
			EST_PED_CP_PED_CP_FORN_VINCULADO.CD_FILIAL = EST_PED_CP_IT.CD_FILIAL AND 
			EST_PED_CP_PED_CP_FORN_VINCULADO.CD_PED = EST_PED_CP_IT.CD_PED
            INNER JOIN EST_PED_CP_PENDENCIA ON 
			EST_PED_CP_PED_CP_FORN_VINCULADO.CD_EMP = EST_PED_CP_PENDENCIA.CD_EMP AND 
			EST_PED_CP_PED_CP_FORN_VINCULADO.CD_FILIAL = EST_PED_CP_PENDENCIA.CD_FILIAL AND 
			EST_PED_CP_PED_CP_FORN_VINCULADO.CD_PED = EST_PED_CP_PENDENCIA.CD_PED
        WHERE 
			EST_PED_CP_IT.CD_EMP IS NULL
			AND EST_PED_CP_PED_CP_FORN_VINCULADO.CD_EMP =1;
/*
        DELETE 
			EST_NF_ENT_PED_CP
        FROM 
			EST_NF_ENT_PED_CP 
			JOIN EST_PED_CP C ON 
			EST_NF_ENT_PED_CP.CD_EMP	= C.CD_EMP AND 
			EST_NF_ENT_PED_CP.CD_FILIAL = C.CD_FILIAL AND 
			EST_NF_ENT_PED_CP.CD_PED	= C.CD_PED

			LEFT OUTER JOIN EST_PED_CP_IT ON 
			C.CD_EMP	= EST_PED_CP_IT.CD_EMP AND 
			C.CD_FILIAL = EST_PED_CP_IT.CD_FILIAL AND 
			C.CD_PED	= EST_PED_CP_IT.CD_PED

            INNER JOIN EST_PED_CP_PENDENCIA ON 
			EST_NF_ENT_PED_CP.CD_EMP	= EST_PED_CP_PENDENCIA.CD_EMP AND 
			EST_NF_ENT_PED_CP.CD_FILIAL = EST_PED_CP_PENDENCIA.CD_FILIAL AND 
			EST_NF_ENT_PED_CP.CD_PED	= EST_PED_CP_PENDENCIA.CD_PED
        WHERE 
			EST_PED_CP_IT.CD_EMP IS NULL
			AND C.CD_EMP=1
			AND C.DT_EMI > GETDATE()-20;
			*/
        
		PRINT 'DELETANDO PEDIDO DE COMPRAS SEM ITENS COM VINCULO COM ELETRONICO - Time ' + convert(varchar(20),getdate(),108);
		DELETE 
			H
        FROM 
			EST_PED_CP INNER JOIN EST_PED_ELTR_FORN_PED_CP H ON 
			EST_PED_CP.CD_EMP = H.CD_EMP AND 
			EST_PED_CP.CD_FILIAL = H.CD_FIL_ENTR AND 
			EST_PED_CP.CD_PED = H.CD_PED
			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
			LEFT OUTER JOIN EST_PED_CP_IT ON 
			EST_PED_CP.CD_EMP = EST_PED_CP_IT.CD_EMP AND 
			EST_PED_CP.CD_FILIAL = EST_PED_CP_IT.CD_FILIAL AND 
			EST_PED_CP.CD_PED = EST_PED_CP_IT.CD_PED
        WHERE 
			EST_PED_CP.CD_EMP = 1
            AND EST_PED_CP_IT.CD_EMP IS NULL;
		
		PRINT 'DELETANDO PEDIDO DE COMPRAS SEM ITENS COM VINCULO COM PRE-ENTRADA - Time ' + convert(varchar(20),getdate(),108);
		DELETE
			H
		FROM 
			EST_PED_CP C INNER JOIN EST_NF_ENT_PRE_ENTRADA H ON 
			C.CD_EMP = H.CD_EMP AND 
			C.CD_FILIAL = H.CD_FILIAL AND 
			C.CD_PED = H.CD_PED 
			INNER JOIN EST_PED_CP_PENDENCIA ON 
			C.CD_EMP = EST_PED_CP_PENDENCIA.CD_EMP AND 
			C.CD_FILIAL = EST_PED_CP_PENDENCIA.CD_FILIAL AND 
			C.CD_PED = EST_PED_CP_PENDENCIA.CD_PED
			LEFT OUTER JOIN EST_PED_CP_IT ON 
			C.CD_EMP = EST_PED_CP_IT.CD_EMP AND 
			C.CD_FILIAL = EST_PED_CP_IT.CD_FILIAL AND 
			C.CD_PED = EST_PED_CP_IT.CD_PED
        WHERE 
			C.CD_EMP = 1
             AND EST_PED_CP_IT.CD_EMP IS NULL;

		PRINT 'DELETANDO PEDIDO SEM ITENS - Time ' + convert(varchar(20),getdate(),108);
		DELETE 
			EST_PED_CP_VINCULADA
		FROM 
			EST_PED_CP_VINCULADA EPCV INNER JOIN EST_PED_CP EPC ON
			EPCV.CD_EMP = EPC.CD_EMP AND
			EPCV.CD_FILIAL = EPC.CD_FILIAL AND
			EPCV.CD_PED = EPC.CD_PED
			LEFT OUTER JOIN EST_PED_CP_IT ON 
			EPC.CD_EMP = EST_PED_CP_IT.CD_EMP AND 
			EPC.CD_FILIAL = EST_PED_CP_IT.CD_FILIAL AND 
			EPC.CD_PED = EST_PED_CP_IT.CD_PED
            INNER JOIN EST_PED_CP_PENDENCIA ON 
			EPC.CD_EMP = EST_PED_CP_PENDENCIA.CD_EMP AND 
			EPC.CD_FILIAL = EST_PED_CP_PENDENCIA.CD_FILIAL AND 
			EPC.CD_PED = EST_PED_CP_PENDENCIA.CD_PED
		WHERE 
			EST_PED_CP_IT.CD_EMP IS NULL
			AND EPC.STS_PED <> 2;
			
        DELETE 
			EST_PED_CP
        FROM 
			EST_PED_CP LEFT OUTER JOIN EST_PED_CP_IT ON 
			EST_PED_CP.CD_EMP = EST_PED_CP_IT.CD_EMP AND 
			EST_PED_CP.CD_FILIAL = EST_PED_CP_IT.CD_FILIAL AND 
			EST_PED_CP.CD_PED = EST_PED_CP_IT.CD_PED
            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 
			EST_PED_CP_IT.CD_EMP IS NULL
            AND EST_PED_CP.STS_PED <> 2;
        
	   PRINT 'LIMPANDO DANFES SEM ITENS PARA REIMPORTACAO - Time ' + convert(varchar(20),getdate(),108);
	   DELETE 
	   EST_NF_ENT_DANFE_PROVISORIO_CIENCIA_OPERACAO
	   FROM 
	   EST_NF_ENT_DANFE_PROVISORIO_CIENCIA_OPERACAO
	   INNER JOIN EST_NF_ENT_DANFE_PROVISORIO_PENDENTE
	   ON EST_NF_ENT_DANFE_PROVISORIO_CIENCIA_OPERACAO.CD_CTR = EST_NF_ENT_DANFE_PROVISORIO_PENDENTE.CD_CTR
	   LEFT OUTER JOIN EST_NF_ENT_DANFE_PROVISORIO_ITENS
	   ON EST_NF_ENT_DANFE_PROVISORIO_CIENCIA_OPERACAO.CD_CTR = EST_NF_ENT_DANFE_PROVISORIO_ITENS.CD_CTR
	   WHERE EST_NF_ENT_DANFE_PROVISORIO_ITENS.CD_CTR IS NULL;
     
	   DELETE 
		  EST_NF_ENT_DANFE_PROVISORIO_CONFIRMACAO_OPERACAO
	   FROM 
		  EST_NF_ENT_DANFE_PROVISORIO_CONFIRMACAO_OPERACAO
		  left JOIN EST_NF_ENT_DANFE_PROVISORIO_PENDENTE ON 
		  EST_NF_ENT_DANFE_PROVISORIO_CONFIRMACAO_OPERACAO.CD_CTR = EST_NF_ENT_DANFE_PROVISORIO_PENDENTE.CD_CTR
		  LEFT OUTER JOIN EST_NF_ENT_DANFE_PROVISORIO_ITENS ON 
		  EST_NF_ENT_DANFE_PROVISORIO_CONFIRMACAO_OPERACAO.CD_CTR = EST_NF_ENT_DANFE_PROVISORIO_ITENS.CD_CTR
	   WHERE EST_NF_ENT_DANFE_PROVISORIO_ITENS.CD_CTR IS NULL;
	   
	   PRINT 'DEVOLUCAO DE FORNECEDOR PENDENCIA BLOQUEIO - Time ' + convert(varchar(20),getdate(),108); 
	   DELETE
			EST_NF_ENT_DANFE_PROVISORIO_BLOQUEIO_PENDENTE
	   FROM 
			EST_NF_ENT_DANFE_PROVISORIO   WITH (NOLOCK)
			INNER JOIN EST_NF_ENT_DANFE_PROVISORIO_BLOQUEIO_PENDENTE ON 
			EST_NF_ENT_DANFE_PROVISORIO.CD_CTR = EST_NF_ENT_DANFE_PROVISORIO_BLOQUEIO_PENDENTE.CD_CTR 
		WHERE
			DS_MOV_DANFE LIKE '%DEVOLUCAO%'
    
	   PRINT 'DEVOLUCAO DE FORNECEDOR PENDENCIA ENTRADA - Time ' + convert(varchar(20),getdate(),108); 
		DELETE
			EST_NF_ENT_DANFE_PROVISORIO_PENDENTE
		FROM 
			EST_NF_ENT_DANFE_PROVISORIO   WITH (NOLOCK)
			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
			DS_MOV_DANFE LIKE '%DEVOLUCAO%'
	
	    PRINT 'CORRIGINDO LIBERACAO DE ENTRADA DE NOTA FISCAL SEM PEDIDO - Time ' + convert(varchar(20),getdate(),108); 
		UPDATE
			EST_NF_ENT_DANFE_PROVISORIO
		SET 
			FLAG_LIBERA_ENTRADA_SEM_PEDIDO=1
		FROM
			EST_NF_ENT_DANFE_PROVISORIO INNER JOIN EST_NF_ENT_DANFE_PROVISORIO_LIBERACAO ON
			EST_NF_ENT_DANFE_PROVISORIO.CD_CTR = EST_NF_ENT_DANFE_PROVISORIO_LIBERACAO.CD_CTR 
		WHERE
			OBS_LIB = 'CADASTRO DO FORNECEDOR CONFIGURADO PARA LIBERAR ENTRADA SEM VINCULO COM O PEDIDO DE COMPRAS'
			AND FLAG_LIBERA_ENTRADA_SEM_PEDIDO=0
			AND EST_NF_ENT_DANFE_PROVISORIO.DT_EMIS_NF >=GETDATE()-5
				
			
		PRINT 'RETIRANDO BLOQUEIO PENDENTE DE NOTA FISCAL EFETIVADA - Time ' + convert(varchar(20),getdate(),108); 	
		DELETE 
			B
		FROM  
			EST_NF_ENT_DANFE_PROVISORIO_BLOQUEIO_PENDENTE  B LEFT OUTER JOIN EST_NF_ENT_DANFE_PROVISORIO_PENDENTE PEND ON
			B.CD_CTR = PEND.CD_CTR  
		WHERE  
			PEND.CD_CTR IS NULL
			AND B.DT_CAD <=GETDATE()-30
    
			CREATE TABLE #RSPEDIDO (CD_EMP INT, CD_FILIAL INT, CD_PED INT, QT_IT MONEY )
			INSERT INTO #RSPEDIDO
			SELECT 
				I.CD_EMP,
				I.CD_FILIAL,
				I.CD_PED,
				(DBO.UFD_EST_PED_CP_IT_SLD (I.CD_EMP,I.CD_FILIAL,I.CD_PED,I.CD_PROD)) AS QT_IT 
			FROM 
			EST_PED_CP_IT I INNER JOIN EST_PED_CP_PENDENCIA P ON
			I.CD_EMP = P.CD_EMP AND
			I.CD_FILIAL = P.CD_FILIAL AND
			I.CD_PED = P.CD_PED 
    
			DELETE
				P
			FROM
			(SELECT
				I.CD_EMP,
				I.CD_FILIAL,
				I.CD_PED
			FROM
				#RSPEDIDO I  
			GROUP BY
				I.CD_EMP,
				I.CD_FILIAL,
				I.CD_PED
			HAVING
				SUM(I.QT_IT)=0) RS INNER JOIN EST_PED_CP_PENDENCIA P ON
				RS.CD_EMP = P.CD_EMP AND
				RS.CD_FILIAL = P.CD_FILIAL AND
				RS.CD_PED = P.CD_PED
    
			DROP TABLE #RSPEDIDO
        /****************************************************************************************************************************/
 	   create table #danfe_deletar (cd_ctr int )
	   print 'insert into #danfe_deletar'
	   insert into #danfe_deletar 
		  select  DANFE.cd_ctr
			 FROM 
			  EST_NF_ENT_DANFE_PROVISORIO DANFE 
			  INNER JOIN EST_NF_ENT_DANFE_PROVISORIO_PENDENTE pend on DANFE.cd_ctr = pend.cd_ctr
			  LEFT OUTER JOIN EST_NF_ENT_DANFE_PROVISORIO_ITENS
			  ON DANFE.CD_CTR = EST_NF_ENT_DANFE_PROVISORIO_ITENS.CD_CTR
			  LEFT JOIN EST_NF_ENT_DANFE_PROVISORIO_EST_NF_ENT on 
			   DANFE.CD_CTR = EST_NF_ENT_DANFE_PROVISORIO_est_nf_ent.CD_CTR
			 WHERE 
			 EST_NF_ENT_DANFE_PROVISORIO_ITENS.CD_CTR IS NULL
			 and EST_NF_ENT_DANFE_PROVISORIO_EST_NF_ENT.CD_CTR IS NULL;
		--RETIRANDO DANFES SEM ITENS
		  PRINT 'RETIRANDO DANFES SEM ITENS'

		  print 'DELETANDO EST_NF_ENT_DANFE_PROVISORIO_BLOQUEIO_PENDENTE'
			 DELETE del
			 FROM EST_NF_ENT_DANFE_PROVISORIO_BLOQUEIO_PENDENTE del
				 INNER JOIN #danfe_deletar deletar ON del.cd_ctr = deletar.cd_ctr;

		  print 'DELETANDO EST_NF_ENT_DANFE_PROVISORIO_BLOQUEIO'  
			  DELETE del
			 FROM EST_NF_ENT_DANFE_PROVISORIO_BLOQUEIO del
				 INNER JOIN #danfe_deletar deletar ON del.cd_ctr = deletar.cd_ctr;

		  print 'DELETANDO EST_NF_ENT_DANFE_PROVISORIO_CHECKIN_ENTRADA'
			 DELETE del
			 FROM EST_NF_ENT_DANFE_PROVISORIO_CHECKIN_ENTRADA del
				 INNER JOIN #danfe_deletar deletar ON del.cd_ctr = deletar.cd_ctr;

		  print 'DELETANDO EST_NF_ENT_DANFE_PROVISORIO_CIENCIA_OPERACAO_PENDENTE'
			 DELETE del
			 FROM EST_NF_ENT_DANFE_PROVISORIO_CIENCIA_OPERACAO_PENDENTE del
				 INNER JOIN #danfe_deletar deletar ON del.cd_ctr = deletar.cd_ctr;

		  print 'DELETANDO EST_NF_ENT_DANFE_PROVISORIO_CIENCIA_OPERACAO'
			 DELETE del
			 FROM EST_NF_ENT_DANFE_PROVISORIO_CIENCIA_OPERACAO del
				 INNER JOIN #danfe_deletar deletar ON del.cd_ctr = deletar.cd_ctr;

		  print 'DELETANDO EST_NF_ENT_DANFE_PROVISORIO_CONFIRMACAO_OPERACAO'
			 DELETE del
			 FROM EST_NF_ENT_DANFE_PROVISORIO_CONFIRMACAO_OPERACAO del
				 INNER JOIN #danfe_deletar deletar ON del.cd_ctr = deletar.cd_ctr;

		  print 'DELETANDO EST_NF_ENT_DANFE_PROVISORIO_CONFIRMACAO_RECBTO'
			 DELETE del
			 FROM EST_NF_ENT_DANFE_PROVISORIO_CONFIRMACAO_RECBTO del
				 INNER JOIN #danfe_deletar deletar ON del.cd_ctr = deletar.cd_ctr;

		  print 'DELETANDO EST_NF_ENT_DANFE_PROVISORIO_DESCONHECIMENTO_OPERACAO_PENDENTE'
			 DELETE del
			 FROM EST_NF_ENT_DANFE_PROVISORIO_DESCONHECIMENTO_OPERACAO_PENDENTE del
				 INNER JOIN #danfe_deletar deletar ON del.cd_ctr = deletar.cd_ctr;

		  print 'DELETANDO EST_NF_ENT_DANFE_PROVISORIO_DESCONHECIMENTO_OPERACAO'
			 DELETE del
			 FROM EST_NF_ENT_DANFE_PROVISORIO_DESCONHECIMENTO_OPERACAO del
				 INNER JOIN #danfe_deletar deletar ON del.cd_ctr = deletar.cd_ctr;
		  print 'DELETANDO EST_NF_ENT_DANFE_PROVISORIO_DUPLICATA'
			 DELETE del
			 FROM EST_NF_ENT_DANFE_PROVISORIO_DUPLICATA del
				 INNER JOIN #danfe_deletar deletar ON del.cd_ctr = deletar.cd_ctr;

		  print 'DELETANDO EST_NF_ENT_DANFE_PROVISORIO_ERROS_VALIDACAO'
			 DELETE del
			 FROM EST_NF_ENT_DANFE_PROVISORIO_ERROS_VALIDACAO del
				 INNER JOIN #danfe_deletar deletar ON del.cd_ctr = deletar.cd_ctr;

		  print 'DELETANDO EST_NF_ENT_DANFE_PROVISORIO_EST_NF_ENT_PRE_ENTRADA'
			 DELETE del
			 FROM EST_NF_ENT_DANFE_PROVISORIO_EST_NF_ENT_PRE_ENTRADA del
				 INNER JOIN #danfe_deletar deletar ON del.cd_ctr = deletar.cd_ctr;

		  print 'DELETANDO EST_NF_ENT_DANFE_PROVISORIO_EST_NF_ENT'
			 DELETE del
			 FROM EST_NF_ENT_DANFE_PROVISORIO_EST_NF_ENT del
				 INNER JOIN #danfe_deletar deletar ON del.cd_ctr = deletar.cd_ctr;

		  print 'DELETANDO EST_NF_ENT_DANFE_PROVISORIO_EST_PED_CP'
			 DELETE del
			 FROM EST_NF_ENT_DANFE_PROVISORIO_EST_PED_CP del
				 INNER JOIN #danfe_deletar deletar ON del.cd_ctr = deletar.cd_ctr;

		  print 'DELETANDO EST_NF_ENT_DANFE_PROVISORIO_FILIAIS'
			 DELETE del
			 FROM EST_NF_ENT_DANFE_PROVISORIO_FILIAIS del
				 INNER JOIN #danfe_deletar deletar ON del.cd_ctr = deletar.cd_ctr;

		  print 'DELETANDO EST_NF_ENT_DANFE_PROVISORIO_ITENS_VALIDACAO_IMPOSTO_ERROS_VALIDACAO'
			 DELETE del
			 FROM EST_NF_ENT_DANFE_PROVISORIO_ITENS_VALIDACAO_IMPOSTO_ERROS_VALIDACAO del
				 INNER JOIN #danfe_deletar deletar ON del.cd_ctr = deletar.cd_ctr;

		  print 'DELETANDO EST_NF_ENT_DANFE_PROVISORIO_ITENS'
			 DELETE del
			 FROM EST_NF_ENT_DANFE_PROVISORIO_ITENS del
				 INNER JOIN #danfe_deletar deletar ON del.cd_ctr = deletar.cd_ctr;

		  print 'DELETANDO EST_NF_ENT_DANFE_PROVISORIO_LIBERACAO_TIPO_BLQ'
			 DELETE del
			 FROM EST_NF_ENT_DANFE_PROVISORIO_LIBERACAO_TIPO_BLQ del
				 INNER JOIN #danfe_deletar deletar ON del.cd_ctr = deletar.cd_ctr;

		  print 'DELETANDO EST_NF_ENT_DANFE_PROVISORIO_LIBERACAO_ENTRADA'	   
			 DELETE del
			 FROM EST_NF_ENT_DANFE_PROVISORIO_LIBERACAO_ENTRADA del
				 INNER JOIN #danfe_deletar deletar ON del.cd_ctr = deletar.cd_ctr;

		  print 'DELETANDO EST_NF_ENT_DANFE_PROVISORIO_LIBERACAO'	   
			 DELETE del
			 FROM EST_NF_ENT_DANFE_PROVISORIO_LIBERACAO del
				 INNER JOIN #danfe_deletar deletar ON del.cd_ctr = deletar.cd_ctr;

		  print 'DELETANDO EST_NF_ENT_DANFE_PROVISORIO_NAO_REALIZADA_OPERACAO_PENDENTE'
			 DELETE del
			 FROM EST_NF_ENT_DANFE_PROVISORIO_NAO_REALIZADA_OPERACAO_PENDENTE del
				 INNER JOIN #danfe_deletar deletar ON del.cd_ctr = deletar.cd_ctr;

		  print 'DELETANDO EST_NF_ENT_DANFE_PROVISORIO_NAO_REALIZADA_OPERACAO'
			 DELETE del
			 FROM EST_NF_ENT_DANFE_PROVISORIO_NAO_REALIZADA_OPERACAO del
				 INNER JOIN #danfe_deletar deletar ON del.cd_ctr = deletar.cd_ctr;

		  print 'DELETANDO EST_NF_ENT_DANFE_PROVISORIO_PENDENTE'
			 DELETE del
			 FROM EST_NF_ENT_DANFE_PROVISORIO_PENDENTE del
				 INNER JOIN #danfe_deletar deletar ON del.cd_ctr = deletar.cd_ctr;

		  print 'DELETANDO EST_NF_ENT_DANFE_PROVISORIO_SEM_PEDIDO'
			 DELETE del
			 FROM EST_NF_ENT_DANFE_PROVISORIO_SEM_PEDIDO del
				 INNER JOIN #danfe_deletar deletar ON del.cd_ctr = deletar.cd_ctr;

		  print 'DELETANDO EST_NF_ENT_DANFE_PROVISORIO_SUSPENSO'
			 DELETE del
			 FROM EST_NF_ENT_DANFE_PROVISORIO_SUSPENSO del
				 INNER JOIN #danfe_deletar deletar ON del.cd_ctr = deletar.cd_ctr;

		  print 'DELETANDO EST_NF_ENT_DANFE_PROVISORIO_TRANSP'
			 DELETE del
			 FROM EST_NF_ENT_DANFE_PROVISORIO_TRANSP del
				 INNER JOIN #danfe_deletar deletar ON del.cd_ctr = deletar.cd_ctr;

		  print 'DELETANDO EST_NF_ENT_DANFE_PROVISORIO_VALIDACAO_IMPOSTO_CONFIRMACAO'
			 DELETE del
			 FROM EST_NF_ENT_DANFE_PROVISORIO_VALIDACAO_IMPOSTO_CONFIRMACAO del
				 INNER JOIN #danfe_deletar deletar ON del.cd_ctr = deletar.cd_ctr;

		  print 'DELETANDO EST_PED_ELTR_EST_NF_ENT_DANFE_PROVISORIO'
			 DELETE del
			 FROM EST_PED_ELTR_EST_NF_ENT_DANFE_PROVISORIO del inner
				 JOIN #danfe_deletar deletar ON del.cd_ctr = deletar.cd_ctr;
	
        /****************************************************************************************************************************/
		CREATE TABLE #RsPedidoAnalise(CD_EMP INT,
									  CD_FILIAL INT,
									  CD_PED INT,
									  VLR_PEDIDO MONEY,
									  VLR_PROD_TOT MONEY,
									  VLR_DESC MONEY,
									  VLR_BASE_SUBS MONEY,
									  VLR_IPI MONEY,
									  VLR_ICMS_SUBS MONEY)
		INSERT INTO #RsPedidoAnalise
		SELECT
			EST_PED_CP_IT.CD_EMP,
			EST_PED_CP_IT.CD_FILIAL,
			EST_PED_CP_IT.CD_PED,
			SUM(((EST_PED_CP_IT.QT_IT*EST_PED_CP_IT.VLR_IT)+EST_PED_CP_IT.VLR_IPI+EST_PED_CP_IT.VLR_ICMS_SUBS)-EST_PED_CP_IT.VLR_DESC) VLR_PEDIDO,
			SUM((EST_PED_CP_IT.QT_IT*EST_PED_CP_IT.VLR_IT)-EST_PED_CP_IT.VLR_DESC) VLR_TOT_IT,
			SUM(EST_PED_CP_IT.VLR_DESC) AS VLR_DESC,
			SUM(EST_PED_CP_IT.VLR_BASE_SUBS) AS VLR_BASE_SUBS,
			SUM(EST_PED_CP_IT.VLR_IPI) AS VLR_IPI,
			SUM(EST_PED_CP_IT.VLR_ICMS_SUBS ) AS VLR_ICMS_SUBS
		FROM
			EST_PED_CP_IT INNER JOIN EST_PED_CP ON
			EST_PED_CP_IT.CD_EMP = EST_PED_CP.CD_EMP AND
			EST_PED_CP_IT.CD_FILIAL = EST_PED_CP.CD_FILIAL AND
			EST_PED_CP_IT.CD_PED = EST_PED_CP.CD_PED
			INNER JOIN EST_PED_CP_PENDENCIA ON
			EST_PED_CP_IT.CD_EMP = EST_PED_CP_PENDENCIA.CD_EMP AND
			EST_PED_CP_IT.CD_FILIAL = EST_PED_CP_PENDENCIA.CD_FILIAL AND
			EST_PED_CP_IT.CD_PED = EST_PED_CP_PENDENCIA.CD_PED
		WHERE
			EST_PED_CP_IT.CD_EMP=1
		GROUP BY
			EST_PED_CP_IT.CD_EMP,
			EST_PED_CP_IT.CD_FILIAL,
			EST_PED_CP_IT.CD_PED,
			EST_PED_CP.VLR_PED
		HAVING 
			SUM(((EST_PED_CP_IT.QT_IT*EST_PED_CP_IT.VLR_IT)+EST_PED_CP_IT.VLR_IPI+EST_PED_CP_IT.VLR_ICMS_SUBS)-EST_PED_CP_IT.VLR_DESC) <> EST_PED_CP.VLR_PED
	
		UPDATE
			P
		SET 
			P.VLR_PED=A.VLR_PEDIDO,
			P.VLR_TOT_PROD=A.VLR_PROD_TOT,
			P.VLR_DESC=A.VLR_DESC,
			P.VLR_BASE_SUBS =A.VLR_BASE_SUBS,
			P.VLR_ICMS_SUBS =A.VLR_ICMS_SUBS,
			P.VLR_IPI =A.VLR_IPI

		FROM
			EST_PED_CP P INNER JOIN #RsPedidoAnalise a ON
			P.CD_EMP = a.CD_EMP AND
			P.CD_FILIAL = a.CD_FILIAL AND
			P.CD_PED = a.CD_PED 

		DROP TABLE #RsPedidoAnalise
				
		
        BEGIN TRY
            DROP TABLE #RSPEDIDO_VENC;
        END TRY
        BEGIN CATCH
        END CATCH;
        BEGIN TRY
            DROP TABLE #TMP_DEL;
        END TRY
        BEGIN CATCH
        END CATCH;
    END;
