/****** Object:  StoredProcedure [dbo].[P_REPROCESSAR_EST_NF_SAI_IT_PRODUTO_CADASTRO]    Script Date: 10/07/2012 10:54:55 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[P_REPROCESSAR_EST_NF_SAI_IT_PRODUTO_CADASTRO]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[P_REPROCESSAR_EST_NF_SAI_IT_PRODUTO_CADASTRO]
GO
GO
--exec P_REPROCESSAR_EST_NF_SAI_IT_PRODUTO_CADASTRO 4,2012
CREATE PROCEDURE [dbo].[P_REPROCESSAR_EST_NF_SAI_IT_PRODUTO_CADASTRO]( @MES INT=NULL, @ANO INT=NULL,@CD_FILIAL_PAR INT=0)  AS

DISABLE TRIGGER TRG_EST_PROD_CPL_ULT_MOV_GLB_MOV_OP_SAIDA ON EST_NF_SAI_IT;
	
	DECLARE @DT_INI DATETIME
	DECLARE @DT_FIM DATETIME
	DECLARE @DIA DATETIME
	DECLARE @CD_FILIAL AS INT
	DECLARE @AGORA DATETIME

	
	SET NOCOUNT ON
	IF @ANO IS NULL OR @MES IS NULL
		begin
			SELECT @AGORA=DATEADD(month, -1, GETDATE()), @ANO=YEAR(@AGORA), @MES=MONTH(@AGORA)
		end
	
	SET @DT_INI = CONVERT(DATETIME, (CONVERT(VARCHAR, (@ANO*100+@MES)) + '01')) ;
	SET @DT_FIM = dbo.F_FINAL_MES (@DT_INI) ;
	
	--RODA SO ATE ONTEM
	IF  @DT_FIM > dbo.F_HOJE()
	BEGIN
		SET @DT_FIM = dbo.F_HOJE() -1 
	END
	
	DECLARE cFilial CURSOR FAST_FORWARD READ_ONLY FOR 
	SELECT  
	 	CD_FILIAL
	FROM 
		PRC_FILIAL
	WHERE 
		CD_EMP = 1  
		AND CD_FILIAL = CASE WHEN @CD_FILIAL_PAR = 0 THEN CD_FILIAL ELSE @CD_FILIAL_PAR END
	OPEN CFILIAL
	FETCH NEXT FROM cFilial INTO @CD_FILIAL

	WHILE @@FETCH_STATUS=0
	BEGIN
		SET @DIA = @DT_INI
		WHILE @DT_FIM >= @DIA
			BEGIN

				PRINT 'Filial ' + CONVERT(VARCHAR, @CD_FILIAL) + ' -  Processando dia  ' + CONVERT(VARCHAR, @DIA, 112) + ' ' + CONVERT(VARCHAR, GETDATE (),108)

				UPDATE 
					EST_NF_SAI_IT 
				SET
					PIS_COFINS				=	p.PIS_COFINS,
					LISTA_PROD				=	p.LISTA_PROD
				FROM
					EST_NF_SAI INNER JOIN EST_NF_SAI_IT ON
					EST_NF_SAI.CD_EMP  = EST_NF_SAI_IT.CD_EMP AND
					EST_NF_SAI.CD_FILIAL = EST_NF_SAI_IT.CD_FILIAL AND
					EST_NF_SAI.CD_NF = EST_NF_SAI_IT.CD_NF 
					INNER JOIN EST_PROD p ON 
					EST_NF_SAI_IT.CD_EMP = p.CD_EMP AND 
					EST_NF_SAI_IT.CD_PROD = p.CD_PROD
				WHERE
					EST_NF_SAI.CD_EMP = 1 
					AND EST_NF_SAI.CD_FILIAL = @CD_FILIAL 
					AND EST_NF_SAI.DT_EMI_NF = @DIA
				
				SELECT @DIA = @DIA + 1
			END		
		FETCH NEXT FROM  cFilial INTO @CD_FILIAL 
	END
CLOSE cFilial;
DEALLOCATE cFilial;

ENABLE TRIGGER TRG_EST_PROD_CPL_ULT_MOV_GLB_MOV_OP_SAIDA ON EST_NF_SAI_IT;	