/*
=======================================================================================
'Nível Classificação.: INFORMAÇÃO RESTRITA
'Versão..............: 202202231100
'Job.................:  
'Nome................: P_EXP_CTB_MOV_DEV_VENDA 
'Objetivo............: 
'Tabelas.............: 
'Dt Criação..........: 13/05/2020
'Criado por..........: 
'Dt Ult Alteracão....: 04/10/2024
'Alterado por........: Gerson Peters Reis e Shirlene Caldeiras

'=======================================================================================
-- Lançar alterações de versão aqui:
Reg #202202231100 - Alteração de variavéis de valores De: ((@VLR_AUX + @VLR_CARTAO_A_PRAZO) - @VLR_NF_ENT) Para: @VLR_NF_ENT - @VLR_AUX.  - Shirlene Campos do Prado Caldeira
*/


IF OBJECT_ID('P_EXP_CTB_MOV_DEV_VENDA') IS NOT NULL
	BEGIN
		DROP PROCEDURE P_EXP_CTB_MOV_DEV_VENDA
	END
 
GO
 
CREATE PROCEDURE P_EXP_CTB_MOV_DEV_VENDA(	@CD_EMP				INT,
											@CD_FILIAL			INT,
											@DT_INI				DATETIME,
											@DT_FIM				DATETIME,
											@FLAG_LIMPAR		INT = 0)		
	
WITH ENCRYPTION AS 
SET NOCOUNT ON;
BEGIN TRY
BEGIN
	
	DECLARE @RS_CD_EMP					INT
	DECLARE @RS_CD_FILIAL				INT
	DECLARE @RS_CD_NF					INT
	DECLARE @RS_DT_ENT					DATETIME
	DECLARE @RS_VLR_NF					MONEY
	DECLARE @RS_CD_VD					INT
	DECLARE @RS_DT_VD					DATETIME
	DECLARE @RS_VLR_LIQ_VD				MONEY
	DECLARE @RS_VLR_DINH				MONEY 
	DECLARE @RS_VLR_CHQS				MONEY
	DECLARE @RS_VLR_CONV				MONEY 
	DECLARE @RS_VLR_CARTAO				MONEY 
	DECLARE @RS_CD_ADM_CARTAO			MONEY
	DECLARE @RS_CD_CLI					INT
	DECLARE @RS_CD_CONV					INT
	DECLARE @RS_TP_DEVO					VARCHAR(50)
	DECLARE @RS_DT_CONTABILIZAR			DATETIME
	DECLARE @RS_NR_CNT_RED				INT
	DECLARE @RS_NR_CNT					VARCHAR(100)
	DECLARE @RS_DS_CONTA				VARCHAR(100)
	DECLARE @RS_DT_MOV					DATETIME
	DECLARE @RS_VLR_DEV_SECAO			MONEY
	DECLARE @RS_VLR_CUSTO_MD			MONEY
	DECLARE @RS_VLR_LANC				MONEY
	DECLARE @RS_VLR_FRETE				MONEY
	
	DECLARE @RS_ORIG_CONTA				VARCHAR(50)
	DECLARE @RS_COD_CONTA				INT
	
	DECLARE @RET_CD_CTB_CNT				VARCHAR(100)
	DECLARE @RET_CD_CTB_CNT_RED			INT	
	
	DECLARE @HIST						VARCHAR(200)
	
	DECLARE @VLR_NF_ENT 				MONEY
	DECLARE @VLR_CHEQUES 				MONEY
	DECLARE @VLR_DUPLICATA				MONEY
	DECLARE @VLR_CARTAO 				MONEY
	DECLARE @VLR_CONVENIO				MONEY				
	DECLARE @VLR_DINDIN					MONEY
	DECLARE @VLR_DINHEIRO				MONEY
	DECLARE @VLR_LIQ_VENDA				MONEY
	DECLARE @VLR_CARTAO_A_VISTA			MONEY
	DECLARE @VLR_CARTAO_A_PRAZO			MONEY
	DECLARE @VLR_CHEQUE_A_VISTA			MONEY
	DECLARE @VLR_CHEQUE_A_PRAZO			MONEY
	DECLARE @VLR_AUX					MONEY
	DECLARE @VLR_TEMP					MONEY
	DECLARE @VLR_CONTA_CAIXA				MONEY
	DECLARE @VLR_CONTA_CHEQUE_A_VISTA		MONEY
	DECLARE @VLR_CONTA_CHEQUE_A_PRAZO		MONEY
	DECLARE @NR_CONTROLE				VARCHAR (12)
	DECLARE @RS_VLR_CONV_PBM				MONEY
	DECLARE @VLR_CONVENIO_PBM		     MONEY 
		
	------------------------------------------------------------------------------------------------------------------------------
	--CRIANDO A TABELA TEMPORARIA ##CTB_EXP_MOV
	------------------------------------------------------------------------------------------------------------------------------
	EXEC P_EXP_CTB_MOV_CRIAR_CTB_EXP_MOV @FLAG_LIMPAR
	
	
	DECLARE @TBL_CARTAO  TABLE (CD_ADM_CARTAO 				INT,
								CD_CLI						INT,
								VLR_CARTAO					MONEY,
								CD_CTB_CNT					VARCHAR(50), 
								CD_CTB_CNT_RED				INT, 
								RZ_CLI						VARCHAR(100),
								DT_MOV						DATETIME)

	DECLARE @TBL_CONV    TABLE (CD_CONV 					INT,
								CD_CLI						INT,
								VLR_CONV					MONEY,
								CD_CTB_CNT					VARCHAR(50), 
								CD_CTB_CNT_RED				INT, 
								DS_CONV						VARCHAR(100),
								DT_MOV						DATETIME)
	
	DECLARE @TBL_OUTROS  TABLE (DT_MOV 						DATETIME,
								VLR_CONTA_CAIXA				MONEY,
								VLR_CONTA_CHEQUE_A_VISTA 	MONEY,
								VLR_CONTA_CHEQUE_A_PRAZO	MONEY,
								VLR_CONVENIO_PBM MONEY,
								VLR_DUPLICATA MONEY,
								VLR_FRETE MONEY)

	DECLARE @TBL_DEVO_VD_CREDITO TABLE( CD_EMP				INT,
										CD_FILIAL			INT,
										DS_CONTA			VARCHAR(100),
										NR_CNT_RED			INT,
										NR_CNT				VARCHAR(50),
										DT_MOV				DATETIME,
										VLR_LANC			MONEY,
										ORIG_CONTA			VARCHAR(50),
										COD_CONTA			INT)



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

	--###############################################################################
	--CURSOR DEVOLUÇÕES PARA CALCULO DAS FORMAS DE RECEBIMENTO
	--###############################################################################											
	DECLARE RS_RESULT
	CURSOR FOR 	
		SELECT	
			CD_EMP				, 
			CD_FILIAL			,
			CD_NF				,
			DT_ENT				,
			VLR_NF				,
			CD_VD				, 
			DT_VD				, 
			VLR_LIQ_VD			, 
			VLR_DINH			, 
			VLR_CHQS			,
			VLR_CONV			, 
			VLR_CARTAO			, 
			CD_ADM_CARTAO		, 
			CD_CLI				,
			CD_CONV				,
			TP_DEVO				,
			VLR_CONV_PBM		,
			VLR_FRETE
    
	   FROM UFD_EXP_CTB_MOV_DEVOLUCOES(@CD_EMP, @CD_FILIAL,@DT_INI, @DT_FIM)
	    -- SELECT * FROM UFD_EXP_CTB_MOV_DEVOLUCOES(1, 1, '20180116', '20180116')
		ORDER BY 
			CD_EMP				, 
			CD_FILIAL			,
			DT_ENT
									
		--Abrindo cursor
		OPEN RS_RESULT
		
		--Atribuindo valores do select nas variáveis
		FETCH NEXT FROM RS_RESULT INTO 
				@RS_CD_EMP				, 
				@RS_CD_FILIAL			,
				@RS_CD_NF				,
				@RS_DT_ENT				,
				@RS_VLR_NF				,
				@RS_CD_VD				, 
				@RS_DT_VD				, 
				@RS_VLR_LIQ_VD			, 
				@RS_VLR_DINH			, 
				@RS_VLR_CHQS			,
				@RS_VLR_CONV			, 
				@RS_VLR_CARTAO			, 
				@RS_CD_ADM_CARTAO		, 
				@RS_CD_CLI				,
				@RS_CD_CONV				,
				@RS_TP_DEVO,
				@RS_VLR_CONV_PBM		,
				@RS_VLR_FRETE
					 
	--Iniciando laço
		WHILE @@FETCH_STATUS = 0
			
			BEGIN	
			
				SET @VLR_NF_ENT 	= Round(@RS_VLR_NF, 2) 
				SET @VLR_CHEQUES 	= Round(@RS_VLR_CHQS, 2)	    
				SET @VLR_CARTAO 	= 0  
				SET @VLR_CONVENIO 	= 0  
				SET @VLR_CONTA_CAIXA = 0  		
				SET @VLR_CONTA_CHEQUE_A_PRAZO = 0  
				SET @VLR_CONTA_CHEQUE_A_VISTA =0  	
				SET @VLR_DINDIN 		= Round(@RS_VLR_DINH, 2)  
				SET @VLR_CONVENIO_PBM	= @RS_VLR_CONV_PBM  

		 
				IF @RS_TP_DEVO <> 'CAIXA' AND @RS_VLR_NF > 0
					BEGIN 
						SELECT  @VLR_CARTAO 	= (CASE WHEN @RS_TP_DEVO = 'CARTAO' 	THEN @RS_VLR_CARTAO ELSE 0 END),
								@VLR_CONVENIO 	= (CASE WHEN @RS_TP_DEVO = 'CONVENIO' 	THEN @RS_VLR_CONV + @VLR_CONVENIO_PBM	ELSE 0 END),
								@VLR_DINHEIRO 	= (CASE WHEN @RS_VLR_DINH > 0 			THEN @RS_VLR_DINH 	ELSE 0 END)
								
								
					END
				
				ELSE
					BEGIN
						SELECT 	@VLR_DINHEIRO	=  (CASE WHEN (@RS_VLR_CARTAO + @RS_VLR_CONV) > 0  THEN  
														(@RS_VLR_CARTAO + @RS_VLR_CONV) 
													ELSE
														(ISNULL(@VLR_DINHEIRO,0) + @RS_VLR_NF)
													END)
						
						SET @VLR_DINDIN 	= @RS_VLR_NF 						
					END
					
				SET @VLR_LIQ_VENDA = Round(@RS_VLR_LIQ_VD, 2) 
				SET @VLR_CARTAO_A_VISTA = 0
				SET @VLR_CARTAO_A_PRAZO = 0
				SET @VLR_CHEQUE_A_VISTA = 0
				SET @VLR_CHEQUE_A_PRAZO = 0
				SET @VLR_DUPLICATA	= (CASE WHEN @RS_TP_DEVO = 'DUPLICATA' 	THEN @VLR_LIQ_VENDA	ELSE 0 END)
	          
	            IF @VLR_CARTAO > 0     
					BEGIN
						IF EXISTS ( SELECT TP_ADM
									FROM RC_ADM_CARTAO T
									WHERE T.CD_EMP = 1 
										  AND T.CD_ADM_CARTAO = 0 
										  AND T.TP_ADM IN (1,3)) 
							BEGIN
			                    SET @VLR_CARTAO_A_VISTA = @VLR_CARTAO 
							END
			               ELSE
							BEGIN
							  SET @VLR_CARTAO_A_PRAZO = @VLR_CARTAO 
				    			END
					  END			
	            
	            
	            IF @VLR_CHEQUES > 0 
					BEGIN
						SELECT
							@VLR_CHEQUE_A_PRAZO = SUM(CASE WHEN @RS_DT_VD <  DT_VENCTO THEN VLR_CHQ 	ELSE 0 END),
							@VLR_CHEQUE_A_VISTA = SUM(CASE WHEN @RS_DT_VD >= DT_VENCTO THEN VLR_CHQ 	ELSE 0 END)
						FROM CHQ_LANC_CPL 
						WHERE 
							CD_EMP = @RS_CD_EMP  AND CD_CHQ IN (SELECT CD_CHQ  FROM PDV_VD_CHQS_CHQ_LANC    WHERE CD_EMP= @CD_EMP AND CD_FILIAL 	= @CD_FILIAL AND CD_VD 	= @RS_CD_VD)
	                
						IF @VLR_LIQ_VENDA < @VLR_CHEQUE_A_VISTA 
							BEGIN
								SET @VLR_CHEQUE_A_VISTA = @VLR_LIQ_VENDA
							END	                
						
		                   IF @VLR_LIQ_VENDA < @VLR_CHEQUE_A_PRAZO  
							BEGIN
								SET @VLR_CHEQUE_A_PRAZO = @VLR_LIQ_VENDA
							END	                
				     END
	            
	            SET @VLR_AUX = 0
	            
	    --        IF @RS_DT_ENT <> @RS_DT_VD AND vl
					--BEGIN
					--	SET @VLR_CONTA_CAIXA = @VLR_CONTA_CAIXA + @VLR_NF_ENT
					--END
	    --        ELSE
					--BEGIN
		              
					    IF @VLR_DINHEIRO > 0  
							BEGIN
								SET @VLR_CONTA_CAIXA = @VLR_CONTA_CAIXA + @VLR_DINDIN 
								SET @VLR_AUX = @VLR_AUX + @VLR_DINDIN  --                 0 +      25,99                       
							END
		                                
		                IF @VLR_NF_ENT > @VLR_AUX  
							BEGIN
			                    If @VLR_CHEQUE_A_VISTA > 0  
									BEGIN
										SET @VLR_TEMP = (CASE WHEN @VLR_AUX + @VLR_CHEQUE_A_VISTA > @VLR_NF_ENT THEN
															(CASE WHEN @VLR_AUX = 0 THEN 
																@VLR_NF_ENT 
															 ELSE 
																((@VLR_AUX + @VLR_CHEQUE_A_VISTA) - @VLR_NF_ENT) 
															 END)
														 ELSE
															@VLR_CHEQUE_A_VISTA
														 END)
										
										SET @VLR_CONTA_CHEQUE_A_VISTA 	= @VLR_CONTA_CHEQUE_A_VISTA + @VLR_TEMP
				                        SET @VLR_AUX 					= @VLR_AUX + @VLR_CHEQUE_A_VISTA	                        
									END
									                   	               
		                                
								IF @VLR_CARTAO_A_VISTA > 0 
			                        BEGIN 						
										SET @VLR_TEMP = (CASE WHEN @VLR_AUX + @VLR_CARTAO_A_VISTA > @VLR_NF_ENT THEN
															(CASE WHEN @VLR_AUX > 0 THEN 
																@VLR_NF_ENT 
															 ELSE 
																((@VLR_AUX + @VLR_CARTAO_A_VISTA) - @VLR_NF_ENT) 
															 END)
														 ELSE
															@VLR_CARTAO_A_VISTA
														 END)
										
										INSERT INTO @TBL_CARTAO
											SELECT  RC_ADM_CARTAO_RC_CLI.CD_ADM_CARTAO,
													RC_ADM_CARTAO_RC_CLI.CD_CLI,
													@VLR_TEMP,
													ISNULL(RC_CLI_CNT_CTB.CD_CTB_CNT,'')    AS CD_CTB_CNT, 
													ISNULL(RC_CLI_CNT_CTB.CD_CTB_CNT_RED,0) AS CD_CTB_CNT_RED, 
												    RC_CLI.RZ_CLI,
													@RS_DT_ENT								AS DT_MOV
											FROM RC_ADM_CARTAO_RC_CLI 
												INNER JOIN RC_CLI ON
													RC_ADM_CARTAO_RC_CLI.CD_EMP 	= RC_CLI.CD_EMP
													AND RC_ADM_CARTAO_RC_CLI.CD_CLI = RC_CLI.CD_CLI
												LEFT OUTER JOIN RC_CLI_CNT_CTB ON 
												    RC_CLI.CD_EMP = RC_CLI_CNT_CTB.CD_EMP AND 
												    RC_CLI.CD_CLI = RC_CLI_CNT_CTB.CD_CLI AND
													RC_CLI_CNT_CTB.TP_CNT_CTB 	= 0													
										    WHERE 
												CD_ADM_CARTAO = @RS_CD_ADM_CARTAO
										
										SET @VLR_AUX = @VLR_AUX + @VLR_CARTAO_A_VISTA
									END
										
										
								IF @VLR_CARTAO_A_PRAZO > 0 
								  
			                        BEGIN 						
										SET @VLR_TEMP = (CASE WHEN @VLR_AUX + @VLR_CARTAO_A_PRAZO > @VLR_NF_ENT THEN
															(CASE WHEN @VLR_AUX > 0 THEN 
																@VLR_NF_ENT 
															 ELSE 
																--((@VLR_AUX + @VLR_CARTAO_A_PRAZO) - @VLR_NF_ENT)
																 @VLR_NF_ENT  - @VLR_AUX
															 END)
														 ELSE
															@VLR_CARTAO_A_PRAZO
														 END)
										
		 
										INSERT INTO @TBL_CARTAO
											SELECT  RC_ADM_CARTAO_RC_CLI.CD_ADM_CARTAO,
													RC_ADM_CARTAO_RC_CLI.CD_CLI,
													@VLR_TEMP,
													ISNULL(RC_CLI_CNT_CTB.CD_CTB_CNT,'')    AS CD_CTB_CNT, 
													ISNULL(RC_CLI_CNT_CTB.CD_CTB_CNT_RED,0) AS CD_CTB_CNT_RED, 
												    RC_CLI.RZ_CLI,
													@RS_DT_ENT								AS DT_MOV													
											FROM RC_ADM_CARTAO_RC_CLI 
												INNER JOIN RC_CLI ON
													RC_ADM_CARTAO_RC_CLI.CD_EMP 	= RC_CLI.CD_EMP
													AND RC_ADM_CARTAO_RC_CLI.CD_CLI = RC_CLI.CD_CLI
												LEFT OUTER JOIN RC_CLI_CNT_CTB ON 
												    RC_CLI.CD_EMP = RC_CLI_CNT_CTB.CD_EMP AND 
												    RC_CLI.CD_CLI = RC_CLI_CNT_CTB.CD_CLI AND
													RC_CLI_CNT_CTB.TP_CNT_CTB 	= 0													
										    WHERE 
												CD_ADM_CARTAO = @RS_CD_ADM_CARTAO
										
										SET @VLR_AUX = @VLR_AUX + @VLR_CARTAO_A_PRAZO
									END
							 
			                    IF @VLR_CHEQUE_A_PRAZO > 0  
									BEGIN
										SET @VLR_TEMP = (CASE WHEN @VLR_AUX + @VLR_CHEQUE_A_PRAZO > @VLR_NF_ENT THEN
															(CASE WHEN @VLR_AUX = 0 THEN 
																@VLR_NF_ENT 
															 ELSE 
																((@VLR_AUX + @VLR_CHEQUE_A_PRAZO) - @VLR_NF_ENT) 
															 END)
														 ELSE
															@VLR_CHEQUE_A_PRAZO
														 END)
										
										SET @VLR_CONTA_CHEQUE_A_PRAZO 	= @VLR_CONTA_CHEQUE_A_PRAZO + @VLR_TEMP
				                        SET @VLR_AUX 					= @VLR_AUX + @VLR_CHEQUE_A_PRAZO	                        
									END
		                
		                		                
					            IF @VLR_CONVENIO > 0 
	 
									BEGIN
										
										IF @VLR_LIQ_VENDA > 0
											BEGIN
												IF @VLR_NF_ENT > @VLR_CONVENIO -- FARMAGOI-28370
													BEGIN
														--SET @VLR_TEMP =(@VLR_CONVENIO/@VLR_LIQ_VENDA)*@VLR_NF_ENT;
														SET @VLR_TEMP = @VLR_CONVENIO-- (@VLR_CONVENIO/@VLR_LIQ_VENDA)*@VLR_NF_ENT;
													END
													ELSE
													BEGIN
														SET @VLR_TEMP = @VLR_NF_ENT - (@VLR_CONTA_CAIXA + @VLR_CONTA_CHEQUE_A_VISTA + @VLR_CONTA_CHEQUE_A_PRAZO );
												END

												--SET @VLR_TEMP =(@VLR_CONVENIO/@VLR_LIQ_VENDA)*@VLR_NF_ENT;
												--SET @VLR_TEMP = @VLR_NF_ENT - (@VLR_CONTA_CAIXA + @VLR_CONTA_CHEQUE_A_VISTA + @VLR_CONTA_CHEQUE_A_PRAZO );
											END
										ELSE
										BEGIN 
											SET @VLR_TEMP = (CASE WHEN @VLR_AUX + @VLR_CONVENIO > @VLR_NF_ENT THEN
																(CASE WHEN @VLR_AUX > 0 THEN 
																	@VLR_NF_ENT 
																 ELSE 
																	((@VLR_AUX + @VLR_CONVENIO) - @VLR_NF_ENT) 
																 END)
															 ELSE
																@VLR_CONVENIO
															 END) 
										END
										 
										INSERT INTO @TBL_CONV
											SELECT  
											        @RS_CD_CONV,
													@RS_CD_CLI,
													@VLR_TEMP,
													ISNULL(RC_CLI_CONV.CD_CTB_CNT,'')    AS CD_CTB_CNT, 
													ISNULL(RC_CLI_CONV.CD_CTB_CNT_RED,0) AS CD_CTB_CNT_RED, 
												    RC_CLI_CONV.DS_CONV,
													@RS_DT_ENT							 AS DT_MOV
											FROM  RC_CLI_CONV 
											WHERE ISNULL(@RS_CD_CLI,0) <> 0 AND ISNULL(@RS_CD_CONV,0) <> 0
											AND RC_CLI_CONV.CD_CONV = @RS_CD_CONV

										SET @VLR_AUX = @VLR_AUX + @VLR_CONVENIO	
										SET @VLR_CONVENIO_PBM = @VLR_CONVENIO_PBM + @VLR_CONVENIO
									END
  		
							END
					--END		
				
				
				INSERT INTO @TBL_OUTROS
					SELECT  @RS_DT_ENT,  
							@VLR_CONTA_CAIXA,  
							@VLR_CONTA_CHEQUE_A_VISTA,
							@VLR_CONTA_CHEQUE_A_PRAZO,
							@VLR_CONVENIO_PBM,
							@VLR_DUPLICATA,
							@RS_VLR_FRETE
					WHERE
						(@VLR_CONTA_CAIXA > 0 OR @VLR_CONTA_CHEQUE_A_VISTA > 0 OR @VLR_CONTA_CHEQUE_A_PRAZO > 0 OR @VLR_CONVENIO_PBM > 0 OR @VLR_DUPLICATA > 0 OR @RS_VLR_FRETE > 0)
					 
				------------------------------------------------------------------------------------------------------------------
				--Próximo registro				
				------------------------------------------------------------------------------------------------------------------
				--Atribuindo valores do select nas variáveis
				FETCH NEXT FROM RS_RESULT INTO 
					@RS_CD_EMP				, 
					@RS_CD_FILIAL			,
					@RS_CD_NF				,
					@RS_DT_ENT				,
					@RS_VLR_NF				,
					@RS_CD_VD				, 
					@RS_DT_VD				, 
					@RS_VLR_LIQ_VD			, 
					@RS_VLR_DINH			, 
					@RS_VLR_CHQS			,
					@RS_VLR_CONV			, 
					@RS_VLR_CARTAO			, 
					@RS_CD_ADM_CARTAO		, 
					@RS_CD_CLI				,
					@RS_CD_CONV				,
					@RS_TP_DEVO				,
					@RS_VLR_CONV_PBM		,
					@RS_VLR_FRETE

			END
		
		CLOSE RS_RESULT
		DEALLOCATE RS_RESULT	

/****************************************************************************************************************************************************/
/****************************************************************************************************************************************************/
/****************************************************************************************************************************************************/
	
	------------------------------------------------------------------------------------------------------------
	--INSERINDO OS DADOS CALCULADOS NA TABELA CREDITO
	------------------------------------------------------------------------------------------------------------
	INSERT INTO @TBL_DEVO_VD_CREDITO
		SELECT  @CD_EMP,
				@CD_FILIAL,
				'CAIXA'						AS DS_CONTA,
				0 							AS NR_CNT_RED,
				''							AS NR_CNT,
				DT_MOV						AS DT_MOV,
				--SUM(VLR_CONTA_CAIXA  + VLR_CONVENIO_PBM	)AS VLR_LANC,
				SUM(VLR_CONTA_CAIXA )AS VLR_LANC,
				'FILIAIS'					     AS ORIG_CONTA,
				0							AS COD_CONTA
		FROM @TBL_OUTROS
		
		WHERE VLR_CONTA_CAIXA > 0 OR 	VLR_CONVENIO_PBM > 0
		GROUP BY DT_MOV		
		
		UNION ALL
		
		SELECT  @CD_EMP,
				@CD_FILIAL,
				'CHEQUES A VISTA'				AS DS_CONTA,
				0 							AS NR_CNT_RED,
				''							AS NR_CNT,
				DT_MOV						AS DT_MOV,
				VLR_CONTA_CHEQUE_A_VISTA 		AS VLR_LANC,
				'FILIAIS'						AS ORIG_CONTA,
				3							AS COD_CONTA
		FROM @TBL_OUTROS
		WHERE VLR_CONTA_CHEQUE_A_VISTA > 0		
		
		UNION ALL
		
		SELECT  @CD_EMP,
				@CD_FILIAL,
				'CHEQUES PRE DATADOS'		     AS DS_CONTA,
				0 							AS NR_CNT_RED,
				''							AS NR_CNT,
				DT_MOV						AS DT_MOV,
				VLR_CONTA_CHEQUE_A_PRAZO 		AS VLR_LANC,
				'FILIAIS'					     AS ORIG_CONTA,
				2							AS COD_CONTA
		FROM @TBL_OUTROS
		WHERE VLR_CONTA_CHEQUE_A_PRAZO > 0						
		
		UNION ALL
		
		SELECT  @CD_EMP,
				@CD_FILIAL,
				'CARTAO: ' + RZ_CLI			AS DS_CONTA,
				CD_CTB_CNT_RED				AS NR_CNT_RED,
				CD_CTB_CNT					AS NR_CNT,
				DT_MOV						AS DT_MOV,
				SUM(VLR_CARTAO)				AS VLR_LANC,
				'CLIENTES'					AS ORIG_CONTA,
				CD_CLI						AS COD_CONTA
		FROM @TBL_CARTAO
		WHERE VLR_CARTAO > 0
		GROUP BY 
				CD_CLI,
				RZ_CLI,
				CD_CTB_CNT_RED,
				CD_CTB_CNT,
				DT_MOV						
		
		UNION ALL
		
		SELECT  @CD_EMP,
				@CD_FILIAL,
				'CONVENIO: ' + DS_CONV		AS DS_CONTA,
				CD_CTB_CNT_RED				AS NR_CNT_RED,
				CD_CTB_CNT					AS NR_CNT,
				DT_MOV						AS DT_MOV,
				SUM(VLR_CONV)				AS VLR_LANC,
				'CONVENIO'					AS ORIG_CONTA,
				CD_CONV						AS COD_CONTA
		FROM @TBL_CONV
		WHERE VLR_CONV > 0			
		GROUP BY 
				CD_CONV,
				DS_CONV,
				CD_CTB_CNT_RED,
				CD_CTB_CNT,
				DT_MOV
		UNION ALL
		
		SELECT  @CD_EMP,
				@CD_FILIAL,
				'DUPLICATAS A RECEBER'				AS DS_CONTA,
				0 							AS NR_CNT_RED,
				''							AS NR_CNT,
				DT_MOV						AS DT_MOV,
				VLR_DUPLICATA 		AS VLR_LANC,
				'FILIAIS'						AS ORIG_CONTA,
				5							AS COD_CONTA
		FROM @TBL_OUTROS
		WHERE VLR_DUPLICATA > 0	
		
		UNION ALL
		
		SELECT  @CD_EMP,
				@CD_FILIAL,
				'SERVIÇO - FRETE'				AS DS_CONTA,
				0 							AS NR_CNT_RED,
				''							AS NR_CNT,
				DT_MOV						AS DT_MOV,
				VLR_FRETE 		AS VLR_LANC,
				'FILIAIS'						AS ORIG_CONTA,
				 62							AS COD_CONTA
		FROM @TBL_OUTROS
		WHERE VLR_FRETE > 0
		ORDER BY DT_MOV
		
		
	--###############################################################################
	--CURSOR DEVOLUÇÕES DE VENDAS
	--###############################################################################
	DECLARE RS_RESULT
	CURSOR FOR 	
		SELECT	
			CD_EMP, 
			CD_FILIAL, 
			VLR_DEV_SECAO, 
			VLR_CUSTO_MD,
			DT_CONTABILIZAR
	
		FROM UFD_EXP_CTB_MOV_DEV_VENDA(@CD_EMP, @CD_FILIAL, @DT_INI, @DT_FIM)
		ORDER BY 
			CD_EMP, 
			CD_FILIAL,
			DT_CONTABILIZAR
									
		--Abrindo cursor
		OPEN RS_RESULT
		
		--Atribuindo valores do select nas variáveis
		FETCH NEXT FROM RS_RESULT INTO 
				@RS_CD_EMP				, 
				@RS_CD_FILIAL			,										
				@RS_VLR_DEV_SECAO		, 
				@RS_VLR_CUSTO_MD		,
				@RS_DT_CONTABILIZAR

		--Iniciando laço
		WHILE @@FETCH_STATUS = 0
			BEGIN					 
				------------------------------------------------------------------------------------------------------------------
				--DEVOLUCAO DE VENDAS - DEBITO - Ctb_Cnt_Devolucao_Vendas
				------------------------------------------------------------------------------------------------------------------
				SET @NR_CONTROLE = RIGHT('000'+CAST(@RS_CD_FILIAL AS VARCHAR(3)),3) +  
				    RIGHT('00'+ CAST( DAY( @RS_DT_CONTABILIZAR) AS VARCHAR),2) + 
					   RIGHT('00'+  CAST( MONTH(@RS_DT_CONTABILIZAR) AS VARCHAR),2) + 
						  RIGHT('00'+ CAST( YEAR(@RS_DT_CONTABILIZAR)AS VARCHAR),2) + '711' -- 7 Movimento 11 - origem conta

				INSERT INTO ##CTB_EXP_MOV  
				
						  (CD_EMP,CD_FILIAL_EXPORT, CD_FILIAL,  CD_MOVIMENTO, MOVIMENTO, OPERACAO, OPERACAO_DEBITO,
						  CD_CNT_RED_CREDITO, CD_CNT_CREDITO, CD_CNT_RED_DEBITO, CD_CNT_DEBITO, DT_MOV, HIST,
						  VLR_LANC, TP_TRANSA, RATEIO_CENTRO_CUSTO, DS_CENTRO_CUSTO, CNT_CENTRO_CUSTO, VLR_CENTRO_CUSTO,
						  ORIG_CONTA, COD_CONTA,NM_PROCEDURE,TIPO_LANCTO, CD_EVENTO, NR_DP, ANO, NR_DOC, CD_BC_LANC)

					SELECT		@RS_CD_EMP										AS CD_EMP,
								@CD_FILIAL										AS CD_FILIAL_EXPORT,
								@RS_CD_FILIAL									AS CD_FILIAL,
								7												AS CD_MOVIMENTO,						
								'DEVOLUCAO DE VENDAS'							AS MOVIMENTO,
								''												AS OPERACAO,
								'DEVOLUCAO - DEBITO'							AS OPERACAO_DEBITO,										
								0												AS CD_CNT_RED_CREDITO,
								''												AS CD_CNT_CREDITO,
								0												AS CD_CNT_RED_DEBITO,
								''												AS CD_CNT_DEBITO,										
								@RS_DT_CONTABILIZAR								AS DT_MOV,																						
								'DEVOLUÇÕES DE VENDAS N/ DATA CONF. NF' 		AS HIST,								
								ROUND(@RS_VLR_DEV_SECAO,2)   					AS VLR_LANC,
								'D'												AS TP_TRANSA,
								0 												AS RATEIO_CENTRO_CUSTO,
								'' 												AS DS_CENTRO_CUSTO,
							     '' 												AS CNT_CENTRO_CUSTO,
								0 												AS VLR_CENTRO_CUSTO,
								'FILIAIS'										AS ORIG_CONTA,
								11												AS COD_CONTA,
								OBJECT_NAME(@@PROCID)							AS NM_PROCEDURE	
								 , 'X' AS TIPO_LANCTO
                                        , 0 AS CD_EVENTO
								, 0  AS NR_DP
								, 0  AS ANO
								, @NR_CONTROLE AS NR_DOC
								, '' AS CD_BC_LANC ;

					------------------------------------------------------------------------------------------------------------------
					--DEVOLUCAO DE VENDAS CUSTO - DEBITO - Ctb_Cnt_Movimento_Estoque
					------------------------------------------------------------------------------------------------------------------

				    SET @NR_CONTROLE = RIGHT('000'+CAST(@RS_CD_FILIAL AS VARCHAR(3)),3) +  
					   RIGHT('00'+ CAST( DAY( @RS_DT_CONTABILIZAR) AS VARCHAR),2) + 
						  RIGHT('00'+  CAST( MONTH(@RS_DT_CONTABILIZAR) AS VARCHAR),2) + 
							 RIGHT('00'+ CAST( YEAR(@RS_DT_CONTABILIZAR)AS VARCHAR),2) + '731' -- 07 Movimento 31 - origem conta


					INSERT INTO ##CTB_EXP_MOV 
								(CD_EMP,CD_FILIAL_EXPORT, CD_FILIAL,  CD_MOVIMENTO, MOVIMENTO, OPERACAO, OPERACAO_DEBITO,
								CD_CNT_RED_CREDITO, CD_CNT_CREDITO, CD_CNT_RED_DEBITO, CD_CNT_DEBITO, DT_MOV, HIST,
								VLR_LANC, TP_TRANSA, RATEIO_CENTRO_CUSTO, DS_CENTRO_CUSTO, CNT_CENTRO_CUSTO, VLR_CENTRO_CUSTO,
								ORIG_CONTA, COD_CONTA,NM_PROCEDURE,TIPO_LANCTO, CD_EVENTO, NR_DP, ANO, NR_DOC, CD_BC_LANC) 
						SELECT		@RS_CD_EMP									AS CD_EMP,
									@CD_FILIAL									AS CD_FILIAL_EXPORT,
									@RS_CD_FILIAL									AS CD_FILIAL,
									7											AS CD_MOVIMENTO,
									'DEVOLUCAO DE VENDAS'							AS MOVIMENTO,
									''											AS OPERACAO,
									'DEVOLUCAO CUSTO - DEBITO'						AS OPERACAO_DEBITO,										
									0											AS CD_CNT_RED_CREDITO,
									''											AS CD_CNT_CREDITO,
									0											AS CD_CNT_RED_DEBITO,
									''											AS CD_CNT_DEBITO,										
									@RS_DT_CONTABILIZAR								AS DT_MOV,																						
									'DEVOLUÇÕES DE VENDAS N/ DATA CONF. NF' 			AS HIST,								
									ROUND(@RS_VLR_CUSTO_MD,2)						AS VLR_LANC,
									'D'											AS TP_TRANSA,
									0 											AS RATEIO_CENTRO_CUSTO,
									'' 											AS DS_CENTRO_CUSTO,
									'' 											AS CNT_CENTRO_CUSTO,
									0 											AS VLR_CENTRO_CUSTO,
									'FILIAIS'										AS ORIG_CONTA,
									32											AS COD_CONTA,
									OBJECT_NAME(@@PROCID)							AS NM_PROCEDURE											
									 , 'X' AS TIPO_LANCTO
								    , 0 AS CD_EVENTO
								    , 0  AS NR_DP
								    , 0  AS ANO
								    , @NR_CONTROLE AS NR_DOC
								    , '' AS CD_BC_LANC;
					------------------------------------------------------------------------------------------------------------------
					--DEVOLUCAO DE VENDAS CUSTO - CREDITO - Ctb_Cnt_Movimento_Vendas_Custo
					------------------------------------------------------------------------------------------------------------------


	      			SET @NR_CONTROLE = RIGHT('000'+CAST(@RS_CD_FILIAL AS VARCHAR(3)),3) +  
					   RIGHT('00'+ CAST( DAY( @RS_DT_CONTABILIZAR) AS VARCHAR),2) + 
						  RIGHT('00'+  CAST( MONTH(@RS_DT_CONTABILIZAR) AS VARCHAR),2) + 
							 RIGHT('00'+ CAST( YEAR(@RS_DT_CONTABILIZAR)AS VARCHAR),2) +'731' -- 7 Movimento 31 - origem conta

					INSERT INTO ##CTB_EXP_MOV
					
							 (CD_EMP,CD_FILIAL_EXPORT, CD_FILIAL,  CD_MOVIMENTO, MOVIMENTO, OPERACAO, OPERACAO_DEBITO,
							 CD_CNT_RED_CREDITO, CD_CNT_CREDITO, CD_CNT_RED_DEBITO, CD_CNT_DEBITO, DT_MOV, HIST,
							 VLR_LANC, TP_TRANSA, RATEIO_CENTRO_CUSTO, DS_CENTRO_CUSTO, CNT_CENTRO_CUSTO, VLR_CENTRO_CUSTO,
							 ORIG_CONTA, COD_CONTA,NM_PROCEDURE,TIPO_LANCTO, CD_EVENTO, NR_DP, ANO, NR_DOC, CD_BC_LANC)  

						SELECT		@RS_CD_EMP									AS CD_EMP,
									@CD_FILIAL									AS CD_FILIAL_EXPORT,
									@RS_CD_FILIAL									AS CD_FILIAL,
									7											AS CD_MOVIMENTO,
									'DEVOLUCAO DE VENDAS'							AS MOVIMENTO,
									'DEVOLUCAO CUSTO - CREDITO'						AS OPERACAO,
									''											AS OPERACAO_DEBITO,										
									0											AS CD_CNT_RED_CREDITO,
									''											AS CD_CNT_CREDITO,
									0											AS CD_CNT_RED_DEBITO,
									''											AS CD_CNT_DEBITO,										
									@RS_DT_CONTABILIZAR								AS DT_MOV,																						
									'DEVOLUÇÕES DE VENDAS N/ DATA CONF. NF' 			AS HIST,								
									ROUND(@RS_VLR_CUSTO_MD,2)						AS VLR_LANC,
									'C'											AS TP_TRANSA,
									0 											AS RATEIO_CENTRO_CUSTO,
									'' 											AS DS_CENTRO_CUSTO,
									'' 											AS CNT_CENTRO_CUSTO,
									0 											AS VLR_CENTRO_CUSTO,
									'FILIAIS'										AS ORIG_CONTA,
									31											AS COD_CONTA,
									OBJECT_NAME(@@PROCID)							AS NM_PROCEDURE	
									 , 'X' AS TIPO_LANCTO
									   , 0 AS CD_EVENTO
									   , 0  AS NR_DP
									   , 0  AS ANO
									   , @NR_CONTROLE AS NR_DOC
									   , '' AS CD_BC_LANC;
			------------------------------------------------------------------------------------------------------------------
			--Próximo registro				
			------------------------------------------------------------------------------------------------------------------
			--Atribuindo valores do select nas variáveis
			FETCH NEXT FROM RS_RESULT INTO 
				@RS_CD_EMP				, 
				@RS_CD_FILIAL			,										
				@RS_VLR_DEV_SECAO		, 
				@RS_VLR_CUSTO_MD		,
				@RS_DT_CONTABILIZAR		

		END
	
	CLOSE RS_RESULT
	DEALLOCATE RS_RESULT
			

	--###############################################################################
	--CURSOR DEVOLUÇÕES DE VENDAS CREDITO
	--###############################################################################									
	DECLARE RS_RESULT
	CURSOR FOR 	
		SELECT	
			CD_EMP				,
			CD_FILIAL			,
			DS_CONTA			,
			NR_CNT_RED			,
			NR_CNT				,
			DT_MOV				,
			SUM(VLR_LANC) AS VLR_LANC,
			ORIG_CONTA			,
			COD_CONTA			
	
		FROM @TBL_DEVO_VD_CREDITO
		GROUP BY 
			CD_EMP				,
			CD_FILIAL			,
			DS_CONTA			,
			NR_CNT_RED			,
			NR_CNT				,
			DT_MOV				,			
			ORIG_CONTA			,
			COD_CONTA
		ORDER BY 
			CD_EMP				,
			CD_FILIAL			,
			DT_MOV
			
		--Abrindo cursor
		OPEN RS_RESULT
		
		--Atribuindo valores do select nas variáveis
		FETCH NEXT FROM RS_RESULT INTO 
				@RS_CD_EMP				, 
				@RS_CD_FILIAL			,					
				@RS_DS_CONTA			,
				@RS_NR_CNT_RED			,
				@RS_NR_CNT				,
				@RS_DT_MOV				,
				@RS_VLR_LANC			,
				@RS_ORIG_CONTA			,
				@RS_COD_CONTA			
					 

		--Iniciando laço
		WHILE @@FETCH_STATUS = 0
			BEGIN	    
			
				------------------------------------------------------------------------------------------------------------------
				--DEVOLUCAO DE VENDAS - CREDITO - CONTAS FORMA DE PAGAMENTO
				------------------------------------------------------------------------------------------------------------------

				SET @NR_CONTROLE = RIGHT('000'+CAST(@RS_CD_FILIAL AS VARCHAR(3)),3) +  
					   RIGHT('00'+ CAST( DAY( @RS_DT_MOV) AS VARCHAR),2) + 
						  RIGHT('00'+  CAST( MONTH(@RS_DT_MOV) AS VARCHAR),2) + 
							 RIGHT('00'+ CAST( YEAR(@RS_DT_MOV)AS VARCHAR),2) + '711'

				INSERT INTO ##CTB_EXP_MOV 
				
					   (CD_EMP,CD_FILIAL_EXPORT, CD_FILIAL,  CD_MOVIMENTO, MOVIMENTO, OPERACAO, OPERACAO_DEBITO,
					   CD_CNT_RED_CREDITO, CD_CNT_CREDITO, CD_CNT_RED_DEBITO, CD_CNT_DEBITO, DT_MOV, HIST,
					   VLR_LANC, TP_TRANSA, RATEIO_CENTRO_CUSTO, DS_CENTRO_CUSTO, CNT_CENTRO_CUSTO, VLR_CENTRO_CUSTO,
					   ORIG_CONTA, COD_CONTA,NM_PROCEDURE,TIPO_LANCTO, CD_EVENTO, NR_DP, ANO, NR_DOC, CD_BC_LANC)
				 
					SELECT		@RS_CD_EMP										AS CD_EMP,
								@CD_FILIAL										AS CD_FILIAL_EXPORT,
								@RS_CD_FILIAL									AS CD_FILIAL,
								7												AS CD_MOVIMENTO,
								'DEVOLUCAO DE VENDAS'							AS MOVIMENTO,
								'DEVOLUCAO - CREDITO'							AS OPERACAO,
								''												AS OPERACAO_DEBITO,										
								@RS_NR_CNT_RED									AS CD_CNT_RED_CREDITO,
								@RS_NR_CNT										AS CD_CNT_CREDITO,
								0												AS CD_CNT_RED_DEBITO,
								''												AS CD_CNT_DEBITO,										
								@RS_DT_MOV										AS DT_MOV,																						
								'DEVOLUÇÕES DE VENDAS N/ DATA CONF. N F: ' + @RS_DS_CONTA	AS HIST,								
								ROUND(@RS_VLR_LANC,2)							AS VLR_LANC,
								'C'												AS TP_TRANSA,
								0 												AS RATEIO_CENTRO_CUSTO,
								'' 												AS DS_CENTRO_CUSTO,
								'' 												AS CNT_CENTRO_CUSTO,
								0 												AS VLR_CENTRO_CUSTO,
								@RS_ORIG_CONTA									AS ORIG_CONTA,
								@RS_COD_CONTA									AS COD_CONTA,
								OBJECT_NAME(@@PROCID)							AS NM_PROCEDURE	
								, 'X' AS TIPO_LANCTO
                                        , 0 AS CD_EVENTO
								, 0  AS NR_DP
								, 0  AS ANO
								, @NR_CONTROLE AS NR_DOC
								, '' AS CD_BC_LANC;
			
			------------------------------------------------------------------------------------------------------------------
			--Próximo registro				
			------------------------------------------------------------------------------------------------------------------
			--Atribuindo valores do select nas variáveis
			FETCH NEXT FROM RS_RESULT INTO 
				@RS_CD_EMP				, 
				@RS_CD_FILIAL			,					
				@RS_DS_CONTA			,
				@RS_NR_CNT_RED			,
				@RS_NR_CNT				,
				@RS_DT_MOV				,
				@RS_VLR_LANC			,
				@RS_ORIG_CONTA			,
				@RS_COD_CONTA			

		END
	
	CLOSE RS_RESULT
	DEALLOCATE RS_RESULT					
				
		
END

END TRY
BEGIN CATCH
	CLOSE RS_RESULT
	DEALLOCATE RS_RESULT	

	INSERT INTO ADM_ERRO (numero, severidade, estado, rotina, linha, mensagem, dtErro)
		SELECT
			ERROR_NUMBER() AS numero,
			ERROR_SEVERITY() AS severidade,
			ERROR_STATE() AS estado,
			ERROR_PROCEDURE() AS rotina,
			ERROR_LINE() AS linha,
			ERROR_MESSAGE() AS mensagem,
			GETDATE() AS dtErro;	
END CATCH					
GO