61b47355a78008dee1dd31ba465f4a76db3f6b29
[freeside.git] / FS / FS / Cron / bill.pm
1 package FS::Cron::bill;
2
3 use strict;
4 use vars qw( @ISA @EXPORT_OK );
5 use Exporter;
6 use Date::Parse;
7 use DBI 1.33; #The "clone" method was added in DBI 1.33. 
8 use FS::UID qw(dbh);
9 use FS::Record qw( qsearch qsearchs );
10 use FS::queue;
11 use FS::cust_main;
12 use FS::part_event;
13 use FS::part_event_condition;
14
15 @ISA = qw( Exporter );
16 @EXPORT_OK = qw ( bill bill_where );
17
18 #freeside-daily %opt:
19 #  -s: re-charge setup fees
20 #  -v: enable debugging
21 #  -l: debugging level
22 #  -m: Experimental multi-process mode uses the job queue for multi-process and/or multi-machine billing.
23 #  -r: Multi-process mode dry run option
24
25 sub bill {
26   my %opt = @_;
27
28   my $check_freq = $opt{'check_freq'} || '1d';
29
30   my $debug = 0;
31   $debug = 1 if $opt{'v'};
32   $debug = $opt{'l'} if $opt{'l'};
33   $FS::cust_main::DEBUG = $debug;
34   #$FS::cust_event::DEBUG = $opt{'l'} if $opt{'l'};
35
36   #we're at now now (and later).
37   $opt{'time'} = $opt{'d'} ? str2time($opt{'d'}) : $^T;
38   $opt{'time'} += $opt{'y'} * 86400 if $opt{'y'};
39
40   $opt{'invoice_time'} = $opt{'n'} ? $^T : $opt{'time'};
41
42   ###
43   # get a list of custnums
44   ###
45
46   my $cursor_dbh = dbh->clone;
47
48   $cursor_dbh->do(
49     "DECLARE cron_bill_cursor CURSOR FOR ".
50     "  SELECT custnum FROM cust_main WHERE ". bill_where( %opt )
51   ) or die $cursor_dbh->errstr;
52
53   while ( 1 ) {
54
55     my $sth = $cursor_dbh->prepare('FETCH 100 FROM cron_bill_cursor'); #mysql?
56
57     $sth->execute or die $sth->errstr;
58
59     my @custnums = map { $_->[0] } @{ $sth->fetchall_arrayref };
60
61     last unless scalar(@custnums);
62
63     ###
64     # for each custnum, queue or make one customer object and bill
65     # (one at a time, to reduce memory footprint with large #s of customers)
66     ###
67     
68     foreach my $custnum ( @custnums ) {
69     
70       my %args = (
71           'time'         => $opt{'time'},
72           'invoice_time' => $opt{'invoice_time'},
73           'actual_time'  => $^T, #when freeside-bill was started
74                                  #(not, when using -m, freeside-queued)
75           'check_freq'   => $check_freq,
76           'resetup'      => ( $opt{'s'} ? $opt{'s'} : 0 ),
77       );
78
79       if ( $opt{'m'} ) {
80
81         if ( $opt{'r'} ) {
82           warn "DRY RUN: would add custnum $custnum for queued_bill\n";
83         } else {
84
85           #avoid queuing another job if there's one still waiting to run
86           next if qsearch( 'queue', { 'job'     => 'FS::cust_main::queued_bill',
87                                       'custnum' => $custnum,
88                                       'status'  => 'new',
89                                     }
90                          );
91
92           #add job to queue that calls bill_and_collect with options
93           my $queue = new FS::queue {
94             'job'      => 'FS::cust_main::queued_bill',
95             'secure'   => 'Y',
96             'priority' => 99, #don't get in the way of provisioning jobs
97           };
98           my $error = $queue->insert( 'custnum'=>$custnum, %args );
99
100         }
101
102       } else {
103
104         my $cust_main = qsearchs( 'cust_main', { 'custnum' => $custnum } );
105         $cust_main->bill_and_collect( %args, 'debug' => $debug );
106
107       }
108
109     }
110
111   }
112
113   $cursor_dbh->commit or die $cursor_dbh->errstr;
114
115 }
116
117 # freeside-daily %opt:
118 #  -d: Pretend it's 'date'.  Date is in any format Date::Parse is happy with,
119 #      but be careful.
120 #
121 #  -y: In addition to -d, which specifies an absolute date, the -y switch
122 #      specifies an offset, in days.  For example, "-y 15" would increment the
123 #      "pretend date" 15 days from whatever was specified by the -d switch
124 #      (or now, if no -d switch was given).
125 #
126 #  -n: When used with "-d" and/or "-y", specifies that invoices should be dated
127 #      with today's date, irregardless of the pretend date used to pre-generate
128 #      the invoices.
129 #
130 #  -p: Only process customers with the specified payby (I<CARD>, I<DCRD>, I<CHEK>, I<DCHK>, I<BILL>, I<COMP>, I<LECB>)
131 #
132 #  -a: Only process customers with the specified agentnum
133 #
134 #  -v: enable debugging
135 #
136 #  -l: debugging level
137
138 sub bill_where {
139   my( %opt ) = @_;
140
141   my $time = $opt{'time'};
142   my $invoice_time = $opt{'invoice_time'};
143
144   my $check_freq = $opt{'check_freq'} || '1d';
145
146   my @search = ();
147
148   push @search, "( cust_main.archived != 'Y' OR archived IS NULL )"; #disable?
149
150   push @search, "cust_main.payby    = '". $opt{'p'}. "'"
151     if $opt{'p'};
152   push @search, "cust_main.agentnum =  ". $opt{'a'}
153     if $opt{'a'};
154
155   if ( @ARGV ) {
156     push @search, "( ".
157       join(' OR ', map "cust_main.custnum = $_", @ARGV ).
158     " )";
159   }
160
161   ###
162   # generate where_pkg/where_event search clause
163   ###
164
165   # select * from cust_main where
166   my $where_pkg = <<"END";
167     EXISTS(
168       SELECT 1 FROM cust_pkg
169         WHERE cust_main.custnum = cust_pkg.custnum
170           AND ( cancel IS NULL OR cancel = 0 )
171           AND (    ( ( setup IS NULL OR setup =  0 )
172                      AND ( start_date IS NULL OR start_date = 0
173                            OR ( start_date IS NOT NULL AND start_date <= $^T )
174                          )
175                    )
176                 OR bill  IS NULL OR bill  <= $time 
177                 OR ( expire  IS NOT NULL AND expire  <= $^T )
178                 OR ( adjourn IS NOT NULL AND adjourn <= $^T )
179               )
180     )
181 END
182
183   my $where_event = join(' OR ', map {
184     my $eventtable = $_;
185
186     my $join  = FS::part_event_condition->join_conditions_sql(  $eventtable );
187     my $where = FS::part_event_condition->where_conditions_sql( $eventtable,
188                                                                 'time'=>$time,
189                                                               );
190
191     my $are_part_event = 
192       "EXISTS ( SELECT 1 FROM part_event $join
193                   WHERE check_freq = '$check_freq'
194                     AND eventtable = '$eventtable'
195                     AND ( disabled = '' OR disabled IS NULL )
196                     AND $where
197               )
198       ";
199
200     if ( $eventtable eq 'cust_main' ) { 
201       $are_part_event;
202     } else {
203       "EXISTS ( SELECT 1 FROM $eventtable
204                   WHERE cust_main.custnum = $eventtable.custnum
205                     AND $are_part_event
206               )
207       ";
208     }
209
210   } FS::part_event->eventtables);
211
212   push @search, "( $where_pkg OR $where_event )";
213
214   warn "searching for customers:\n". join("\n", @search). "\n"
215     if $opt{'v'} || $opt{'l'};
216
217   join(' AND ', @search);
218
219 }
220
221 1;