/****** Object:  StoredProcedure [dbo].[P_ADM_ERRO_PDV_VD_INTEGRACOES_REPROCESSAR]    Script Date: 10/21/2013 11:39:07 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[P_ADM_ERRO_PDV_VD_INTEGRACOES_REPROCESSAR]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[P_ADM_ERRO_PDV_VD_INTEGRACOES_REPROCESSAR]
GO
GO
GO
GO
CREATE PROCEDURE P_ADM_ERRO_PDV_VD_INTEGRACOES_REPROCESSAR AS
/*
	Esta procedure roda dentra da P_EST_PROD_VD_PROC_ALL
*/
SET NOCOUNT ON;
--Deletando movimento com fechamento de caixa bloqueado
DELETE
FROM
	ADM_ERRO_PDV_VD_INTEGRACOES
WHERE  
	(LAUDO LIKE '%FECHAMENTO DE CAIXA BLOQUEADO PARA ALTERACA%' )

CREATE TABLE  #RsProcCupom (CD_CONTROLE INT)
INSERT INTO #RsProcCupom
(CD_CONTROLE)
SELECT
	CD_CONTROLE
FROM
	ADM_ERRO_PDV_VD_INTEGRACOES
WHERE  
	(LAUDO LIKE '%Connection has already been closed%' 
        OR LAUDO LIKE '%deadlock%' or LAUDO LIKE '%PK_BC_LANC%' 
		or LAUDO LIKE '%PDV_CONSLD_VD_MOVIMENTO_REPROCESSAR%' 
		or LAUDO LIKE '%EST_PROD_CPL_VD_LOTE_PROC_PENDENTE%'
		OR LAUDO LIKE '%Diferenca Venda x Recebimento%'
		OR LAUDO LIKE '%with the FOREIGN KEY constraint "FK_PDV_VD_IT_PDV_VD"%'
		OR LAUDO LIKE '%Could not roll back JDBC transaction%'
		or LAUDO LIKE '%PK_RC_VD_CONV%'
		or LAUDO LIKE '%FOREIGN KEY constraint "FK_PDV_VD_IT_FIDELI_CARTAO_PDV_VD_IT"%'
		or LAUDO LIKE '%Diferenca Venda x Total dos Itens%'
		or LAUDO LIKE '%PK_BC_LANC%'
		or LAUDO LIKE '%EST_PROD_CPL_VD_LOTE_PROC_PRC_FILIAL%'
		or LAUDO LIKE '%connection is already closed due to connection error%')
		AND REPROCESSADO = 1
		AND TENTATIVA_RECONSOLIDAR<=10

INSERT INTO PDV_CONSLD_VD_CUPOM_PENDENCIA
(CD_EMP,
CD_FILIAL,
DT_VD,
NR_ECF,
CD_CX,
CD_USU,
DT_CAD,
TP_CUPOM,
NR_ECF_UUID,
RECEIPT_URI)
SELECT
	ADM_ERRO_PDV_VD_INTEGRACOES.CD_EMP,
	ADM_ERRO_PDV_VD_INTEGRACOES.CD_FILIAL,
	ADM_ERRO_PDV_VD_INTEGRACOES.DT_VD,
	ADM_ERRO_PDV_VD_INTEGRACOES.NR_ECF,
	ADM_ERRO_PDV_VD_INTEGRACOES.CD_CX,
	1,
	GETDATE(),
	ADM_ERRO_PDV_VD_INTEGRACOES.TP_CUPOM,
	ADM_ERRO_PDV_VD_INTEGRACOES.NR_ECF_UUID,
	ADM_ERRO_PDV_VD_INTEGRACOES.RECEIPT_URI
FROM
	ADM_ERRO_PDV_VD_INTEGRACOES LEFT OUTER JOIN PDV_CONSLD_VD_CUPOM_PENDENCIA ON
	ADM_ERRO_PDV_VD_INTEGRACOES.CD_EMP = PDV_CONSLD_VD_CUPOM_PENDENCIA.CD_EMP AND
	ADM_ERRO_PDV_VD_INTEGRACOES.CD_FILIAL = PDV_CONSLD_VD_CUPOM_PENDENCIA.CD_FILIAL AND
	ADM_ERRO_PDV_VD_INTEGRACOES.NR_ECF = PDV_CONSLD_VD_CUPOM_PENDENCIA.NR_ECF AND
	ADM_ERRO_PDV_VD_INTEGRACOES.CD_CX = PDV_CONSLD_VD_CUPOM_PENDENCIA.CD_CX AND
	ADM_ERRO_PDV_VD_INTEGRACOES.DT_VD = PDV_CONSLD_VD_CUPOM_PENDENCIA.DT_VD
	INNER JOIN #RsProcCupom c ON
	ADM_ERRO_PDV_VD_INTEGRACOES.CD_CONTROLE = c.CD_CONTROLE
WHERE  
	PDV_CONSLD_VD_CUPOM_PENDENCIA.DT_VD IS NULL; 

update
	e
set
	e.TENTATIVA_RECONSOLIDAR=TENTATIVA_RECONSOLIDAR+1,
	e.DT_TENTATIVA_RECONSOLIDAR=GETDATE()
from
	ADM_ERRO_PDV_VD_INTEGRACOES e inner join #RsProcCupom c on
	e.CD_CONTROLE = c.CD_CONTROLE

DROP TABLE #RsProcCupom;