/****** Object:  StoredProcedure [dbo].[P_PG_CRED_HISTORICO]    Script Date: 03/26/2014 10:46:14 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[P_PG_CRED_HISTORICO]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[P_PG_CRED_HISTORICO]
GO
GO
-- exec P_PG_CRED_HISTORICO 
CREATE PROCEDURE [dbo].[P_PG_CRED_HISTORICO] @DT_PROC DATETIME=NULL WITH ENCRYPTION AS 
	SET NOCOUNT ON	
	DECLARE @DT_FIM DATETIME, @DIA DATETIME
	DECLARE @CD_FILIAL AS INT
	DECLARE @CD_EMP INT
	DECLARE @DT_ATUAL DATETIME
	DECLARE @CD_CTR INT

	SET @DT_ATUAL=GETDATE()
	
    DECLARE CfiliaisPagarProc CURSOR FAST_FORWARD FOR 
		SELECT 
			CD_EMP,
			CD_FILIAL,
			CONVERT(CHAR(10),DT_PROC,112) AS DT_PROC
		FROM	
			PG_CRED_POSICAO_FINANCEIRA_PROCESSAR 
		ORDER BY CD_FILIAL
	OPEN CfiliaisPagarProc

	SET @DT_FIM= CONVERT(CHAR(10),@DT_ATUAL,112)

	FETCH NEXT FROM CfiliaisPagarProc INTO @CD_EMP,@CD_FILIAL,@DT_PROC
		WHILE @@FETCH_STATUS=0
		  begin
			PRINT 'Filial ' + CONVERT(VARCHAR, @CD_FILIAL)
				SET @DIA = @DT_PROC
				WHILE @DT_FIM >= @DIA
				BEGIN
					PRINT 'Processando dia fechamento posicao financeira filial.:  ' + CONVERT(VARCHAR, @DIA, 112) + ' ' + CONVERT(VARCHAR, GETDATE (),108)
					exec P_PG_CRED_HISTORICO_FILIAL @CD_EMP,@CD_FILIAL,@DIA

					--Deletando datas duplicadas
					DELETE 
						PG_CRED_POSICAO_FINANCEIRA_PROCESSAR 
					WHERE 
						CD_EMP=@CD_EMP 
						AND CD_FILIAL=@CD_FILIAL 
						AND DT_PROC <= @DIA
						AND CD_CTR<>@CD_CTR
											
					--Marcando processo ja efetuado
					UPDATE 
						PG_CRED_POSICAO_FINANCEIRA_PROCESSAR
					SET
						DT_PROC=@DIA,
						DT_ULT_PROC=GETDATE()
					WHERE
						CD_CTR=@CD_CTR
											
					SELECT @DIA = @DIA + 1
				END		
				
				DELETE FROM PG_CRED_POSICAO_FINANCEIRA_PROCESSAR WHERE CD_EMP=@CD_EMP AND CD_FILIAL=@CD_FILIAL AND DT_PROC <= @DIA

			FETCH NEXT FROM CfiliaisPagarProc INTO @CD_EMP,@CD_FILIAL,@DT_PROC
		  end

PRINT 'Concluido.'
CLOSE CfiliaisPagarProc;
DEALLOCATE CfiliaisPagarProc;

EXEC P_PG_FORN_PG_CRED_SALDO_ABERTO_PROC @DT_PROC