truncate table dbt_list_sum;
truncate table dbt_list_type1;
drop procedure if exists lt1_accounting_cash_sum_bal;
-- 일단  현금계정만 추가함.

DELIMITER //
create procedure lt1_accounting_cash_sum_bal( _listToken varchar(21), _sdate varchar(8), _edate varchar(8), 
_s1 varchar(32), _e1 varchar(32), _s2 varchar(32), _e2 varchar(32), 
_s3 varchar(32), _e3 varchar(32), _s4 varchar(32), _e4 varchar(32), 
_where varchar(386), _having varchar(386), _orderby varchar(64), 
_branch int, _storage int)

SQL SECURITY INVOKER
BEGIN

Declare _sbal_date varchar(8);
Declare _ebal_date varchar(8);

Declare _sbet1 varchar(64);
Declare _ebet1 varchar(64);
Declare _sbet2 varchar(64);
Declare _ebet2 varchar(64);

if _is_first_date(_sdate) then
	set _sbal_date = '19000101';
	set _ebal_date = '19000101';
else
	set _sbal_date = _sdate;
	set _ebal_date = _edate;
end if;

if _s1 != '' and _e1 != '' then
	set _sbet1 = _s1;
	set _ebet1 = _e1;
else
	set _sbet1 = '!';
	set _ebet1 = '駾';
end if;

if _s2 != '' and _e2 != '' then
	set _sbet2 = _s2;
	set _ebet2 = _e2;
else
	set _sbet2 = '!';
	set _ebet2 = '駾';
end if;

-- 전월 잔액 --
insert into dbt_list_sum
	( created_on, list_token, h_id, id, c1, c2, 
	  d1, d2, d3, d4, 
	  order_by )

-- 이월 현금 잔액 --
select unix_timestamp(), _listToken, mx.id, mx.id, title_code, title_name,
	bal_amt, 0, 0, 0,
	title_code
from 
	( select acc_title_id, (dr_bal_amt - cr_bal_amt) as bal_amt
		from dbr_bal_acc_title
		where yyyy_mm = _prev_month(_sdate) and branch_id = _branch
	) as last_mbal 
	inner join dbr_acc_title as mx on mx.id = last_mbal.acc_title_id
where ( title_code = '1101'  );
-- 일단  현금계정만 추가함.

-- 입출금 합계 --
insert into dbt_list_sum
	( created_on, list_token, h_id, id, c1, c2, 
	  d1, d2, d3, d4, 
	  order_by )
select unix_timestamp(), _listToken, 1, 1, '1101', '현금',
	0, sum(slip_amt*cast((collect_status+1)/2 as int)), sum(slip_amt*cast(-1*(collect_status-1)/2 as int)), sum(slip_amt*collect_status),
	'1101'
from 
    ( select id,  branch_id, deal_type_id, slip_amt
        from dbr_acc_slip
        where acc_date between _sdate and _edate
			and deal_type_id between 21 and 25
	) as sbhd
	inner join dbr_deal_type as deal on deal.id = sbhd.deal_type_id
where branch_id = _branch
group by branch_id;

-- dbt_list_type1 으로 집계 --
insert into dbt_list_type1
	( created_on, list_token, h_id, id, c1, c2, 
		d1, d2, d3, d4,
		order_by )
select min(unix_timestamp()), min(_listToken), min(id), min(id), min(c1), min(c2),
	sum(d1),
	sum(d2),
	sum(d3),
	sum(d1) + sum(d2) - sum(d3),
	min(order_by)
from dbt_list_sum as mx
where list_token = _listToken
group by mx.id
having min(mx.id) is not null
order by order_by asc;

END;
//
DELIMITER ; 