do 
$$
declare
    _list refcursor;
    _item record;
    _vl_tot numeric;
begin

    open _list for
      select distinct
          tb_nf_item.id_emp,
          tb_nf_item.id_nf,
          tb_nf.id_vnd,
          tb_nf.dt_emis
      from tb_nf_item
      join tb_nf on
          (tb_nf_item.id_emp = tb_nf.id_emp and
           tb_nf_item.id_nf = tb_nf.id_nf)
      join tb_item on
          (tb_nf_item.id_item = tb_item.id_item)
      join tb_tp_item on
          (tb_item.id_tp_item = tb_tp_item.id_tp_item)
      where
          (tb_tp_item.item_nf = false or
           tb_tp_item.item_nf is null) and
          tb_nf.tp_emis = '[P]' and
          tb_nf.sit not in ('8', '7');
          

    
    loop
        fetch _list into _item;
        
        exit when not found;
        
        delete from tb_nf_item
        where
            id_nf = _item.id_nf and
            id_item in (select tb_item.id_item
                        from tb_item
                        join tb_tp_item on
                            tb_item.id_tp_item = tb_tp_item.id_tp_item
                        where
                            tb_tp_item.item_nf = false or
                            tb_tp_item.item_nf is null);
                            
        select sum(tb_nf_item.vl_tot) into _vl_tot
        from tb_nf_item
        where
            id_nf = _item.id_nf;
        
        update tb_nf set 
            vl_item = _vl_tot,
            vl_nf = _vl_tot
        where
            id_nf = _item.id_nf;
            
        delete from tb_nf_parc
        where
            id_nf = _item.id_nf;
            
        raise notice 'NF ID: %', _item.id_nf;
    
    end loop;
        
end
$$