1 package FS::Cron::bill;
4 use vars qw( @ISA @EXPORT_OK );
8 use FS::Record qw(qsearchs);
11 use FS::part_event_condition;
13 @ISA = qw( Exporter );
14 @EXPORT_OK = qw ( bill );
20 my $check_freq = $opt{'check_freq'} || '1d';
23 $debug = 1 if $opt{'v'};
24 $debug = $opt{'l'} if $opt{'l'};
26 $FS::cust_main::DEBUG = $debug;
27 #$FS::cust_event::DEBUG = $opt{'l'} if $opt{'l'};
31 push @search, "cust_main.payby = '". $opt{'p'}. "'"
33 push @search, "cust_main.agentnum = ". $opt{'a'}
38 join(' OR ', map "cust_main.custnum = $_", @ARGV ).
43 # generate where_pkg/where_event search clause
46 #we're at now now (and later).
47 my($time)= $opt{'d'} ? str2time($opt{'d'}) : $^T;
48 $time += $opt{'y'} * 86400 if $opt{'y'};
50 my $invoice_time = $opt{'n'} ? $^T : $time;
52 # select * from cust_main where
53 my $where_pkg = <<"END";
54 0 < ( select count(*) from cust_pkg
55 where cust_main.custnum = cust_pkg.custnum
56 and ( cancel is null or cancel = 0 )
57 and ( setup is null or setup = 0
58 or bill is null or bill <= $time
59 or ( expire is not null and expire <= $^T )
60 or ( adjourn is not null and adjourn <= $^T )
65 my $where_event = join(' OR ', map {
68 my $join = FS::part_event_condition->join_conditions_sql( $eventtable );
69 my $where = FS::part_event_condition->where_conditions_sql( $eventtable,
74 "0 < ( SELECT COUNT(*) FROM part_event $join
75 WHERE check_freq = '$check_freq'
76 AND eventtable = '$eventtable'
77 AND ( disabled = '' OR disabled IS NULL )
82 if ( $eventtable eq 'cust_main' ) {
85 "0 < ( SELECT COUNT(*) FROM $eventtable
86 WHERE cust_main.custnum = $eventtable.custnum
92 } FS::part_event->eventtables);
94 push @search, "( $where_pkg OR $where_event )";
97 # get a list of custnums
100 warn "searching for customers:\n". join("\n", @search). "\n"
101 if $opt{'v'} || $opt{'l'};
103 my $sth = dbh->prepare(
104 "SELECT custnum FROM cust_main".
105 " WHERE ". join(' AND ', @search)
106 ) or die dbh->errstr;
108 $sth->execute or die $sth->errstr;
110 my @custnums = map { $_->[0] } @{ $sth->fetchall_arrayref };
113 # for each custnum, queue or make one customer object and bill
114 # (one at a time, to reduce memory footprint with large #s of customers)
117 foreach my $custnum ( @custnums ) {
121 'invoice_time' => $invoice_time,
122 'actual_time' => $^T, #when freeside-bill was started
123 #(not, when using -m, freeside-queued)
124 'check_freq' => $check_freq,
125 'resetup' => ( $opt{'s'} ? $opt{'s'} : 0 ),
130 #add job to queue that calls bill_and_collect with options
131 my $queue = new FS::queue {
132 'job' => 'FS::cust_main::queued_bill',
135 my $error = $queue->insert( 'custnum'=>$custnum, %args );
139 my $cust_main = qsearchs( 'cust_main', { 'custnum' => $custnum } );
140 $cust_main->bill_and_collect( %args, 'debug' => $debug );