drop table if exists {p_i07tbl1};
/*peg_end*/

drop table if exists {p_i07tbl2};
/*peg_end*/


/**************************
     create temp for i01
**************************/
create table {p_i07tbl1}
select i07.*, 
       sum(i07.p06) as p06tot, 
       if(i07.p06<0, -1, 1) as i01p012
from i07
where p06<>0
   && p011<>'' 
GROUP BY i07.p01, i07.p02, i07.p04, if(i07.p06<0, -1, 1);
/*peg_end*/

update {p_i07tbl1} set nr01=0;
/*peg_end*/
  
update {p_i07tbl1} set nr01=peg_new_nr01('i01', 1);
/*peg_end*/
  
/****************
    i01
*****************/    
INSERT INTO i01
(nr01, p01, p02, p03, p04, p013, p011, p022, p05, p012, p610, p0601, pd01, pd101, 
remdate, remtime, remuser, remfdate, remftime, remfuser)
SELECT i07.nr01 as nr01, 
       i07.p02 as p01, 
       i07.vp02 as p02, 
       abs(i07.p06tot) as p03, 
       i07.p04 as p04, 
       '{odbcdtos(np_dt)}' as p013, 
       round(i07.p06tot*i07.p04, 2) as p011, 
       round(i07.p06tot*i07.p04, 2) as p022, 
       {np_kk} as p05, 
       /*i01.p012=-1 for negative balances*/
       i01p012 as p012,  
       i07.p01 as p610, 
       concat('{peg_str1}', ' S.N.') as p0601, 
       '{peg_str2}_s' as pd01, 
       'i07' as pd101, 
       
       curdate() as remdate, 
       curtime() as remtime, 
       '{user_pswd}' as remuser, 
       curdate() as remfdate, 
       curtime() as remftime, 
       '{user_pswd}' as remfuser
FROM {p_i07tbl1} as i07;
/*peg_end*/   


/********************************
   create temp for i32
*********************************/   
create table {p_i07tbl2}
SELECT i07.nr01 as nr01, 
       {p_i07tbl1}.nr01 as p00, 
       i07.p02 as p01,
       i07.p011 as p02, 
       1 as p010, 
       i07.p06 as i07p06,

       curdate() as remdate, 
       curtime() as remtime, 
       '{user_pswd}' as remuser, 
       curdate() as remfdate, 
       curtime() as remftime, 
       '{user_pswd}' as remfuser
FROM {p_i07tbl1}, i07
WHERE {p_i07tbl1}.p01=i07.p01
   && {p_i07tbl1}.p02=i07.p02
   && {p_i07tbl1}.p04=i07.p04
   && {p_i07tbl1}.i01p012=if(i07.p06<0, -1, 1)
   && i07.p06<>0
   && i07.p011<>'' ;
/*peg_end*/
