IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[P_ANALISE_VENDA_PRODUTOS_DIARIA_FILIAL_ATU_VD]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[P_ANALISE_VENDA_PRODUTOS_DIARIA_FILIAL_ATU_VD ]
GO 
SET ANSI_NULLS ON
GO 
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE  P_ANALISE_VENDA_PRODUTOS_DIARIA_FILIAL_ATU_VD (@CD_EMP INT=1, @CD_FILIAL INT, @DT_ATUAL DATETIME=NULL)
AS
DECLARE @DEPOSITO AS INT

	IF @DT_ATUAL IS NULL
	BEGIN
		SET @DT_ATUAL =   dbo.F_ONTEM()
	END 

	SET @DEPOSITO =ISNULL((SELECT FLAG_DEPO FROM
		V_PRC_FILIAL_DEPOSITO
		WHERE 
			CD_EMP=@CD_EMP
			AND CD_FILIAL=@CD_FILIAL
			AND FLAG_DEPO=1),0);
			 
	IF  OBJECT_ID('TEMPDB.DBO.#TBL_V') IS NOT NULL
	BEGIN
		 DROP TABLE #TBL_V
	END

	CREATE TABLE #TBL_V ( CD_PROD			INT,
						QTDE_IT			MONEY,
						VLR_TOTAL_VD	MONEY,
						VLR_DESC_VD		MONEY);
	IF @DEPOSITO =0 
	BEGIN
		INSERT INTO #TBL_V
		SELECT	
			CD_PROD, 
			QTDE_IT      = SUM(PDV_VD_IT.QT_IT),
			VLR_TOTAL_VD = SUM(PDV_VD_IT.TOT_IT - PDV_VD_IT.VLR_DESC_TOT_RAT),
			VLR_DESC_VD  = SUM(ROUND(PDV_VD_IT.QT_IT * PDV_VD_IT.VLR_IT * PDV_VD_IT.TX_DESC / 100, 2) + PDV_VD_IT.VLR_OFERTA)
		FROM  
			PDV_VD 
			INNER JOIN PDV_VD_IT ON
			PDV_VD.CD_EMP = PDV_VD_IT.CD_EMP AND
			PDV_VD.CD_FILIAL =PDV_VD_IT.CD_FILIAL AND
			PDV_VD.CD_VD = PDV_VD_IT.CD_VD AND
			PDV_VD.DT_VD = PDV_VD_IT.DT_VD   
		WHERE 
			PDV_VD_IT.CD_EMP=@CD_EMP 
			AND PDV_VD_IT.CD_FILIAL=@CD_FILIAL 
			AND PDV_VD_IT.DT_VD=@DT_ATUAL
			AND PDV_VD.ST_VD = 0
			AND PDV_VD_IT.ST_IT = 1
		GROUP BY 
			PDV_VD_IT.CD_PROD;	
	END
	ELSE
	BEGIN

		INSERT INTO #TBL_V
		SELECT	
			CD_PROD, 
			QTDE_IT      = SUM(PDV_VD_IT.QT_IT),
			VLR_TOTAL_VD = SUM(PDV_VD_IT.TOT_IT - PDV_VD_IT.VLR_DESC_TOT_RAT),
			VLR_DESC_VD  = SUM(ROUND(PDV_VD_IT.QT_IT * PDV_VD_IT.VLR_IT * PDV_VD_IT.TX_DESC / 100, 2) + PDV_VD_IT.VLR_OFERTA)
		FROM  
			PDV_VD 
			INNER JOIN PDV_VD_IT ON
			PDV_VD.CD_EMP = PDV_VD_IT.CD_EMP AND
			PDV_VD.CD_FILIAL =PDV_VD_IT.CD_FILIAL AND
			PDV_VD.CD_VD = PDV_VD_IT.CD_VD AND
			PDV_VD.DT_VD = PDV_VD_IT.DT_VD 
			INNER JOIN   V_PRC_FILIAL_DEPOSITO D ON 
			PDV_VD.CD_EMP = D.CD_EMP AND
			PDV_VD.CD_FILIAL =D.CD_FILIAL 
		WHERE 
			PDV_VD_IT.CD_EMP=@CD_EMP 
			AND D.CD_FILIAL_DEPO=@CD_FILIAL 
			AND PDV_VD_IT.DT_VD=@DT_ATUAL
			AND PDV_VD.ST_VD = 0
			AND PDV_VD_IT.ST_IT = 1
		GROUP BY 
			PDV_VD_IT.CD_PROD;	

	END
	UPDATE A
	SET
		QT_VD_DIA=V.QTDE_IT,
		VLR_MEDIO_VD=V.VLR_TOTAL_VD,
		VLR_DESC_VD=V.VLR_dESC_VD
	FROM 
		#TBL_V V
		INNER JOIN EST_PROD_CPL_ANALISE_DIARIO  A ON 
		V.CD_PROD= A.CD_PROD
	WHERE
		A.CD_EMP=@CD_EMP
		AND A.CD_FILIAL=@CD_FILIAL
		AND A.DT_vD=@DT_ATUAL
