-<%once>
-
-sub owed {
- my($start, $end, %opt) = @_;
-
- my @where = ();
-
- #handle start and end ranges
-
- #24h * 60m * 60s
- push @where, "cust_bill._date <= extract(epoch from now())-".
- ($start * 86400)
- if $start;
-
- push @where, "cust_bill._date > extract(epoch from now()) - ".
- ($end * 86400)
- if $end;
-
- #handle 'cust' option
-
- push @where, "cust_main.custnum = cust_bill.custnum"
- if $opt{'cust'};
-
- #handle 'agentnum' option
- my $join = '';
- if ( $opt{'agentnum'} ) {
- $join = 'LEFT JOIN cust_main USING ( custnum )';
- push @where, "agentnum = '$opt{'agentnum'}'";
- }
-
- my $where = scalar(@where) ? 'WHERE '.join(' AND ', @where) : '';
-
- my $as = $opt{'noas'} ? '' : "as owed_${start}_$end";
-
- my $charged = <<END;
-sum( charged
- - coalesce(
- ( select sum(amount) from cust_bill_pay
- where cust_bill.invnum = cust_bill_pay.invnum )
- ,0
- )
- - coalesce(
- ( select sum(amount) from cust_credit_bill
- where cust_bill.invnum = cust_credit_bill.invnum )
- ,0
- )
-
- )
-END
-
- "coalesce( ( select $charged from cust_bill $join $where ) ,0 ) $as";
-
-}
-
-</%once>