IF OBJECT_ID('P_EST_NF_ENT_CORRECAO') IS NOT NULL
	BEGIN
		DROP PROCEDURE [dbo].[P_EST_NF_ENT_CORRECAO]
	END
GO 
GO
--EXEC P_EST_NF_ENT_CORRECAO
CREATE procedure [dbo].[P_EST_NF_ENT_CORRECAO] AS
declare @dt_processo datetime

Set @dt_processo = convert(char(10),getdate()-2,112)

update
	est_nf_ent_it
set
	est_nf_ent_it.vlr_it = round(est_nf_ent_it.vlr_it,4),
	est_nf_ent_it.VLR_TOT_IT = (est_nf_ent_it.qt_it * round(est_nf_ent_it.vlr_it,4)),
	est_nf_ent_it.VLR_DESC = ROUND(est_nf_ent_it.VLR_DESC,4)
from
	est_nf_ent inner join est_nf_ent_it on
	est_nf_ent.cd_emp = est_nf_ent_it.cd_emp and
	est_nf_ent.cd_filial = est_nf_ent_it.cd_filial and
	est_nf_ent.cd_nf = est_nf_ent_it.cd_nf
	inner join EST_NF_ENT_NFE_PEND on
	est_nf_ent.cd_emp = EST_NF_ENT_NFE_PEND.cd_emp and
	est_nf_ent.cd_filial = EST_NF_ENT_NFE_PEND.cd_filial and
	est_nf_ent.cd_nf = EST_NF_ENT_NFE_PEND.cd_nf
where
	est_nf_ent.cd_emp = 1
	and est_nf_ent.dt_emi_nf >= @dt_processo
	and est_nf_ent_it.VLR_DESC > 0
	and (est_nf_ent_it.qt_it * round(est_nf_ent_it.vlr_it,2)) <> est_nf_ent_it.VLR_TOT_IT

DECLARE @RS TABLE (CD_EMP INT, CD_FILIAL INT, CD_NF INT, VLR_TOT_PROD MONEY)	
INSERT INTO @RS 	
select
	est_nf_ent.cd_emp,
	est_nf_ent.cd_filial,
	est_nf_ent.cd_nf,
	sum((est_nf_ent_it.VLR_TOT_IT))	
from
	est_nf_ent inner join est_nf_ent_it on
	est_nf_ent.cd_emp = est_nf_ent_it.cd_emp and
	est_nf_ent.cd_filial = est_nf_ent_it.cd_filial and
	est_nf_ent.cd_nf = est_nf_ent_it.cd_nf
	inner join EST_NF_ENT_NFE_PEND on
	est_nf_ent.cd_emp = EST_NF_ENT_NFE_PEND.cd_emp and
	est_nf_ent.cd_filial = EST_NF_ENT_NFE_PEND.cd_filial and
	est_nf_ent.cd_nf = EST_NF_ENT_NFE_PEND.cd_nf
	INNER JOIN EST_NFE_LOTE_ENT ON
	est_nf_ent.cd_emp = EST_NFE_LOTE_ENT.cd_emp and
	est_nf_ent.cd_filial = EST_NFE_LOTE_ENT.cd_filial and
	est_nf_ent.cd_nf = EST_NFE_LOTE_ENT.cd_nf	
where
	est_nf_ent.cd_emp = 1
	and est_nf_ent.dt_emi_nf >= @dt_processo
	and EST_NF_ENT_NFE_PEND.pend_soluc = 1
group by
	est_nf_ent.cd_emp,
	est_nf_ent.cd_filial,
	est_nf_ent.cd_nf,
	est_nf_ent.VLR_NF,
	est_nf_ent.VLR_TOT_PROD,
	est_nf_ent.vlr_icms,
	est_nf_ent.vlr_base_icms
HAVING 
	count(est_nf_ent.cd_nf) = 1

UPDATE
	nf
SET
	nf.VLR_TOT_PROD = r.VLR_TOT_PROD,
	nf.FLAG_NF_PROD_TOTAL_BRUTO = 1
FROM
	est_nf_ent nf INNER JOIN @RS r ON
	nf.CD_EMP = r.CD_EMP AND
	nf.CD_FILIAL = r.CD_FILIAL AND
	nf.CD_NF = r.CD_NF 
	
UPDATE
	nf
SET
	nf.PEND_SOLUC = 0
FROM
	EST_NF_ENT_NFE_PEND nf INNER JOIN @RS r ON
	nf.CD_EMP = r.CD_EMP AND
	nf.CD_FILIAL = r.CD_FILIAL AND
	nf.CD_NF = r.CD_NF
GO


