ALTER PROCEDURE "DBA"."dk_reg_koond_earved"( in a_skoop integer, in a_peralg date, in a_perlop date)
BEGIN
  delete from gl_dk_arvetas;
  delete from gl_dk_arvetas2007;
  insert into gl_dk_arvetas( asutnr,arvenr,arvekuup,arvesumma,arvesumma2)
    select dk_kanne.asutnr,dk_kanne.arvenr,dk_kanne.arvekuup,
           sum(if dk_kanne.sisse=1 then (-1)*(dk_kanne.summa) else (dk_kanne.summa) endif),
           sum(if dk_kanne.sisse=1 then (-1)*(dk_kanne.summa2) else (dk_kanne.summa2) endif)
      from dk_kanne key left outer join dk_obj
      where (dk_obj.skoop=a_skoop or a_skoop=0) and dk_obj.spank=1 and dk_kanne.asutnr is not null and (dk_kanne.arvekuup>=a_peralg and dk_kanne.arvekuup<=a_perlop)
      group by dk_kanne.asutnr,dk_kanne.arvekuup,dk_kanne.arvenr;
  insert into gl_dk_arvetas( asutnr,arvenr,arvekuup,makssumma,makssumma2)
    select existid_asulist(Left(dk_earve.sellerregnumber,11),Left(dk_earve.sellername,50),'','') as earve_asutnr,
           Left(dk_earve.invoicenumber,20) as earve_arvenr,
           dk_earve.invoicedate as earve_arvekuup,
           sum(if dk_earve_rida.summa is null then get_eak_itemsum(dk_earve_rida.id_dk_earve,dk_earve_rida."id") else dk_earve_rida.summa endif),
           sum(if dk_earve_rida.summa2 is null then if dk_earve_rida.vatsum is null then 0 else dk_earve_rida.vatsum endif else dk_earve_rida.summa2 endif)
      from dk_earve_rida left outer join dk_earve on dk_earve_rida.id_dk_earve = dk_earve."id"
      where (dk_earve.skoop=a_skoop or a_skoop=0) and Length(Trim(dk_earve.sellername))>0 and (earve_arvekuup>=a_peralg and earve_arvekuup<=a_perlop)
      group by earve_asutnr,earve_arvekuup,earve_arvenr;
  -- koond
  insert into gl_dk_arvetas2007( asutnr,arvenr,arvekuup,arvesumma,arvesumma2,makssumma,makssumma2) 
    select gl_dk_arvetas.asutnr,gl_dk_arvetas.arvenr,gl_dk_arvetas.arvekuup,sum(gl_dk_arvetas.arvesumma),sum(gl_dk_arvetas.arvesumma2),sum(gl_dk_arvetas.makssumma),sum(gl_dk_arvetas.makssumma2)
      from gl_dk_arvetas
      group by gl_dk_arvetas.asutnr,gl_dk_arvetas.arvenr,gl_dk_arvetas.arvekuup;
  -- nullid
  update gl_dk_arvetas2007 set arvesumma=0 where arvesumma is null;
  update gl_dk_arvetas2007 set arvesumma2=0 where arvesumma2 is null;
  update gl_dk_arvetas2007 set makssumma=0 where makssumma is null;
  update gl_dk_arvetas2007 set makssumma2=0 where makssumma2 is null;
END