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 my $invoice_time = $opt{'n'} ? $^T : $time;
29 # select * from cust_main where
30 my $where_pkg = <<"END";
31 0 < ( select count(*) from cust_pkg
32 where cust_main.custnum = cust_pkg.custnum
33 and ( cancel is null or cancel = 0 )
34 and ( setup is null or setup = 0
35 or bill is null or bill <= $time
36 or ( expire is not null and expire <= $^T )
42 my $where_bill_event = <<"END";
43 0 < ( select count(*) from cust_bill
44 where cust_main.custnum = cust_bill.custnum
47 ( select sum(amount) from cust_bill_pay
48 where cust_bill.invnum = cust_bill_pay.invnum )
52 ( select sum(amount) from cust_credit_bill
53 where cust_bill.invnum = cust_credit_bill.invnum )
56 and 0 < ( select count(*) from part_bill_event
57 where payby = cust_main.payby
58 and ( disabled is null or disabled = '' )
59 and seconds <= $time - cust_bill._date
60 and 0 = ( select count(*) from cust_bill_event
61 where cust_bill.invnum = cust_bill_event.invnum
62 and part_bill_event.eventpart = cust_bill_event.eventpart
70 my $extra_sql = ( scalar(%search) ? ' AND ' : ' WHERE ' ). "( $where_pkg OR $where_bill_event )";
74 @cust_main = map { qsearchs('cust_main', { custnum => $_, %search } ) } @ARGV
76 @cust_main = qsearch('cust_main', \%search, '', $extra_sql );
81 foreach $cust_main ( @cust_main ) {
83 # $^T not $time because -d is for pre-printing invoices
84 foreach my $cust_pkg (
85 grep { $_->expire && $_->expire <= $^T } $cust_main->ncancelled_pkgs
87 my $error = $cust_pkg->cancel;
88 warn "Error cancelling expired pkg ". $cust_pkg->pkgnum. " for custnum ".
89 $cust_main->custnum. ": $error"
92 # $^T not $time because -d is for pre-printing invoices
93 foreach my $cust_pkg (
94 grep { $_->part_pkg->is_prepaid
95 && $_->bill && $_->bill < $^T && ! $_->susp
97 $cust_main->ncancelled_pkgs
99 my $action = $cust_pkg->part_pkg->option('recur_action') || 'suspend';
100 my $error = $cust_pkg->$action();
101 warn "Error suspending package ". $cust_pkg->pkgnum.
102 " for custnum ". $cust_main->custnum.
107 my $error = $cust_main->bill( 'time' => $time,
108 'invoice_time' => $invoice_time,
109 'resetup' => $opt{'s'},
111 warn "Error billing, custnum ". $cust_main->custnum. ": $error" if $error;
113 $cust_main->apply_payments_and_credits;
115 $error = $cust_main->collect( 'invoice_time' => $time,
116 'freq' => $opt{'freq'},
118 warn "Error collecting, custnum". $cust_main->custnum. ": $error" if $error;