IF EXISTS(SELECT * FROM sys.objects 
			WHERE object_id=OBJECT_ID(N'[dbo].[p_remove_pdv_vd_it]') AND type IN(N'P',N'PC')
)
    DROP PROCEDURE dbo.p_remove_pdv_vd_it;
GO
GO

CREATE PROCEDURE [dbo].[p_remove_pdv_vd_it]
(
     @cd_emp    INT
    ,@cd_filial INT
    ,@cd_vd     INT)
AS

BEGIN
set CONTEXT_INFO  0x77777 ;

declare @Cmd varchar (1000);


	DELETE FROM pdv_vd_it_est_sngpc_pendente
	WHERE
		  cd_emp = @cd_emp
		  AND cd_filial = @cd_filial
		  AND cd_vd = @cd_vd;

	IF EXISTS(SELECT 1 FROM pdv_vd_it_est_sngpc_saida
				WHERE cd_emp = @cd_emp
					  AND cd_filial = @cd_filial
					  AND cd_vd = @cd_vd)
		BEGIN
			
			RAISERROR ('Alteracao nao permitida - Cupom com lançamento no sngpc',16, 1);
			ROLLBACK TRANSACTION;
			RETURN;

			--DELETE FROM pdv_vd_it_est_sngpc_saida
			--WHERE
			--	  cd_emp = @cd_emp
			--	  AND cd_filial = @cd_filial
			--	  AND cd_vd = @cd_vd;
			
		END;
			
	DELETE FROM PDV_VD_IT_EST_SNGPC_PENDENTE_CANCELADO
	WHERE
		  cd_emp = @cd_emp
		  AND cd_filial = @cd_filial
		  AND cd_vd = @cd_vd;
 
																 
	  
-- :::::::::::::::::::::::::::::::::::::::					
 CREATE TABLE #TEMP_RC_CLI_FIDELI_PONTOS_CREDITO ( CD_CTR_PONTOS INT ) 
  
	INSERT INTO #TEMP_RC_CLI_FIDELI_PONTOS_CREDITO
	SELECT CD_CTR_PONTOS 
	  FROM RC_CLI_FIDELI_PONTOS_CREDITO_PDV_VD_IT_FIDELI_CARTAO
	 WHERE CD_EMP    = @CD_EMP
	   AND CD_FILIAL = @CD_FILIAL
	   AND CD_VD     = @CD_VD

	DELETE 
	  FROM RC_CLI_FIDELI_PONTOS_CREDITO_PDV_VD_IT_FIDELI_CARTAO
 	 WHERE CD_EMP        = @CD_EMP
 	   AND CD_FILIAL     = @CD_FILIAL
	   AND CD_VD         = @CD_VD

	DELETE FROM A 
	  FROM RC_CLI_FIDELI_PONTOS_CREDITO A 
		   INNER JOIN #TEMP_RC_CLI_FIDELI_PONTOS_CREDITO B ON A.CD_CTR_PONTOS = B.CD_CTR_PONTOS				   
		   
-- :::::::::::::::::::::::::::::::::::::::
	  	
	DELETE FROM RC_CLI_FIDELI_PONTOS_DEBITO_PDV_VD_IT
	WHERE
		  cd_emp = @cd_emp
		  AND cd_filial = @cd_filial
		  AND cd_vd = @cd_vd;

	DELETE FROM pdv_vd_it_vd_pbm
	WHERE
		  cd_emp = @cd_emp
		  AND cd_filial = @cd_filial
		  AND cd_vd = @cd_vd;

	DELETE FROM pdv_vd_it_operador_caixa_comissao
	WHERE
		  cd_emp = @cd_emp
		  AND cd_filial = @cd_filial
		  AND cd_vd = @cd_vd;
	
	--Devolve os itens para o estoque
	update c
	set
		qt_est=Qt_est + i.QtEST
	from		  		  
		(SELECT 
			CD_EMP,
			CD_PROD,
			CD_FILIAL,
			SUM(QT_IT) QtEst
		FROM 
			pdv_vd_it with(nolock)
		WHERE
				cd_emp = @cd_emp
			AND cd_filial = @cd_filial
			AND cd_vd = @cd_vd
			and st_it=1
		group by CD_EMP,
			CD_PROD,
			CD_FILIAL)  I
		join est_prod_cpl c on 
		i.CD_EMP	= c.CD_EMP and
		i.CD_PROD	= c.CD_PROD and
		i.CD_FILIAL	= c.CD_FILIAL
	WHERE
		C.cd_emp = @cd_emp
	AND C.cd_filial = @cd_filial;

	Set @Cmd = 'DELETE FROM pdv_vd_it WHERE cd_emp = ' + convert(varchar, @cd_emp) + ' AND cd_filial = ' + convert(varchar, @cd_filial ) + ' AND cd_vd = ' + convert(varchar,@cd_vd) +' ;'

	EXEC(@Cmd);

END
