select fc_en_trg(false, false);

update tb_nf set 
    dt_op = dt_emis 
where 
    id_mod_nf = '01' and tp_emis = '[P]';

update tb_nf_item set 
    id_trib_icms = '090',
    id_trib_ipi = '99',
    id_trib_pis = '01',
    id_trib_cofins = '01',
    vl_aliq_pis = 1.65,
    vl_bc_pis = vl_tot,
    vl_pis = 1.65 * vl_tot / 100,
    vl_aliq_cofins = 7.60,
    vl_bc_cofins = vl_tot,
    vl_cofins = 7.60 * vl_tot / 100,
    id_cfop = 5104
from tb_nf
where 
    tb_nf.id_emp = tb_nf_item.id_emp and
    tb_nf.id_nf = tb_nf_item.id_nf and
    tb_nf.id_mod_nf = '01' and 
    tb_nf.tp_emis = '[P]';
    
    
update tb_nf set
    vl_nf = (select sum(vl_tot - vl_desc)
              from tb_nf_item
              where
                  tb_nf.id_emp = tb_nf_item.id_emp and
                  tb_nf.id_nf = tb_nf_item.id_nf),
    vl_pis = (select sum(vl_pis)
              from tb_nf_item
              where
                  tb_nf.id_emp = tb_nf_item.id_emp and
                  tb_nf.id_nf = tb_nf_item.id_nf),
    vl_cofins = (select sum(vl_cofins)
              from tb_nf_item
              where
                  tb_nf.id_emp = tb_nf_item.id_emp and
                  tb_nf.id_nf = tb_nf_item.id_nf)
where 
    id_mod_nf = '01' and tp_emis = '[P]';

--
-- zera pis e cofins para nota de devolucao
--
update tb_nf_item set 
    vl_aliq_pis = 0,
    vl_bc_pis = 0,
    vl_pis = 0,
    vl_aliq_cofins = 0,
    vl_bc_cofins = 0,
    vl_cofins = 0
from tb_nf
where 
    tb_nf.id_emp = tb_nf_item.id_emp and
    tb_nf.id_nf = tb_nf_item.id_nf and
    tb_nf.id_nat_op = 6;
    
    
update tb_nf set
    vl_pis = (select sum(vl_pis)
              from tb_nf_item
              where
                  tb_nf.id_emp = tb_nf_item.id_emp and
                  tb_nf.id_nf = tb_nf_item.id_nf),
    vl_cofins = (select sum(vl_cofins)
              from tb_nf_item
              where
                  tb_nf.id_emp = tb_nf_item.id_emp and
                  tb_nf.id_nf = tb_nf_item.id_nf)
where 
    tb_nf.id_nat_op = 6;

select fc_en_trg(true, false);









update tb_nf_item set 
    vl_aliq_pis = 0,
    vl_bc_pis = 0,
    vl_pis = 0,
    vl_aliq_cofins = 0,
    vl_bc_cofins = 0,
    vl_cofins = 0
from tb_nf
where 
    tb_nf.id_emp = tb_nf_item.id_emp and
    tb_nf.id_nf = tb_nf_item.id_nf and
    tb_nf.tp_emis = '[P]';
    
    
update tb_nf set
    vl_pis = (select sum(vl_pis)
              from tb_nf_item
              where
                  tb_nf.id_emp = tb_nf_item.id_emp and
                  tb_nf.id_nf = tb_nf_item.id_nf),
    vl_cofins = (select sum(vl_cofins)
              from tb_nf_item
              where
                  tb_nf.id_emp = tb_nf_item.id_emp and
                  tb_nf.id_nf = tb_nf_item.id_nf)
where 
    tp_emis = '[P]' and
    dt_emisa >= '2014-11-01'