1 package FS::Cron::bill;
4 use vars qw( @ISA @EXPORT_OK );
7 use FS::Record qw(qsearch qsearchs);
10 @ISA = qw( Exporter );
11 @EXPORT_OK = qw ( bill );
17 $FS::cust_main::DEBUG = 1 if $opt{'v'};
20 $search{'payby'} = $opt{'p'} if $opt{'p'};
21 $search{'agentnum'} = $opt{'a'} if $opt{'a'};
23 #we're at now now (and later).
24 my($time)= $opt{'d'} ? str2time($opt{'d'}) : $^T;
25 $time += $opt{'y'} * 86400 if $opt{'y'};
27 # select * from cust_main where
28 my $where_pkg = <<"END";
29 0 < ( select count(*) from cust_pkg
30 where cust_main.custnum = cust_pkg.custnum
31 and ( cancel is null or cancel = 0 )
32 and ( setup is null or setup = 0
33 or bill is null or bill <= $time
34 or ( expire is not null and expire <= $^T )
40 my $where_bill_event = <<"END";
41 0 < ( select count(*) from cust_bill
42 where cust_main.custnum = cust_bill.custnum
45 ( select sum(amount) from cust_bill_pay
46 where cust_bill.invnum = cust_bill_pay.invnum )
50 ( select sum(amount) from cust_credit_bill
51 where cust_bill.invnum = cust_credit_bill.invnum )
54 and 0 < ( select count(*) from part_bill_event
55 where payby = cust_main.payby
56 and ( disabled is null or disabled = '' )
57 and seconds <= $time - cust_bill._date
58 and 0 = ( select count(*) from cust_bill_event
59 where cust_bill.invnum = cust_bill_event.invnum
60 and part_bill_event.eventpart = cust_bill_event.eventpart
68 my $extra_sql = ( scalar(%search) ? ' AND ' : ' WHERE ' ). "( $where_pkg OR $where_bill_event )";
72 @cust_main = map { qsearchs('cust_main', { custnum => $_, %search } ) } @ARGV
74 @cust_main = qsearch('cust_main', \%search, '', $extra_sql );
79 foreach $cust_main ( @cust_main ) {
81 # $^T not $time because -d is for pre-printing invoices
82 foreach my $cust_pkg (
83 grep { $_->expire && $_->expire <= $^T } $cust_main->ncancelled_pkgs
85 my $error = $cust_pkg->cancel;
86 warn "Error cancelling expired pkg ". $cust_pkg->pkgnum. " for custnum ".
87 $cust_main->custnum. ": $error"
90 # $^T not $time because -d is for pre-printing invoices
91 foreach my $cust_pkg (
92 grep { $_->part_pkg->is_prepaid
93 && $_->bill && $_->bill < $^T && ! $_->susp
95 $cust_main->ncancelled_pkgs
97 my $error = $cust_pkg->suspend;
98 warn "Error suspending package ". $cust_pkg->pkgnum.
99 " for custnum ". $cust_main->custnum.
104 my $error = $cust_main->bill( 'time' => $time,
105 'resetup' => $opt{'s'},
107 warn "Error billing, custnum ". $cust_main->custnum. ": $error" if $error;
109 $cust_main->apply_payments_and_credits;
111 $error = $cust_main->collect( 'invoice_time' => $time,
112 'freq' => $opt{'freq'},
114 warn "Error collecting, custnum". $cust_main->custnum. ": $error" if $error;