This commit was generated by cvs2svn to compensate for changes in r10640,
[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 driver_name );
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 #  -g: Don't bill these pkgparts
25
26 sub bill {
27   my %opt = @_;
28
29   my $check_freq = $opt{'check_freq'} || '1d';
30
31   my $debug = 0;
32   $debug = 1 if $opt{'v'};
33   $debug = $opt{'l'} if $opt{'l'};
34   $FS::cust_main::DEBUG = $debug;
35   #$FS::cust_event::DEBUG = $opt{'l'} if $opt{'l'};
36
37   my $conf = new FS::Conf;
38   if ( $conf->exists('disable_cron_billing') ) {
39     warn "disable_cron_billing set, skipping billing\n" if $debug;
40     return;
41   }
42
43   #we're at now now (and later).
44   $opt{'time'} = $opt{'d'} ? str2time($opt{'d'}) : $^T;
45   $opt{'time'} += $opt{'y'} * 86400 if $opt{'y'};
46
47   $opt{'invoice_time'} = $opt{'n'} ? $^T : $opt{'time'};
48
49   #hashref here doesn't work with -m
50   #my $not_pkgpart = $opt{g} ? { map { $_=>1 } split(/,\s*/, $opt{g}) }
51   #                          : {};
52
53   ###
54   # get a list of custnums
55   ###
56
57   my $cursor_dbh = dbh->clone;
58
59   my $select = 'SELECT custnum FROM cust_main WHERE '. bill_where( %opt );
60
61   unless ( driver_name =~ /^mysql/ ) {
62     $cursor_dbh->do( "DECLARE cron_bill_cursor CURSOR FOR $select" )
63       or die $cursor_dbh->errstr;
64   }
65
66   while ( 1 ) {
67
68     my $sql = (driver_name =~ /^mysql/)
69       ? $select
70       : 'FETCH 100 FROM cron_bill_cursor';
71
72     my $sth = $cursor_dbh->prepare($sql);
73
74     $sth->execute or die $sth->errstr;
75
76     my @custnums = map { $_->[0] } @{ $sth->fetchall_arrayref };
77
78     last unless scalar(@custnums);
79
80     ###
81     # for each custnum, queue or make one customer object and bill
82     # (one at a time, to reduce memory footprint with large #s of customers)
83     ###
84     
85     foreach my $custnum ( @custnums ) {
86     
87       my %args = (
88           'time'         => $opt{'time'},
89           'invoice_time' => $opt{'invoice_time'},
90           'actual_time'  => $^T, #when freeside-bill was started
91                                  #(not, when using -m, freeside-queued)
92           'check_freq'   => $check_freq,
93           'resetup'      => ( $opt{'s'} ? $opt{'s'} : 0 ),
94           'not_pkgpart'  => $opt{'g'}, #$not_pkgpart,
95       );
96
97       if ( $opt{'m'} ) {
98
99         if ( $opt{'r'} ) {
100           warn "DRY RUN: would add custnum $custnum for queued_bill\n";
101         } else {
102
103           #avoid queuing another job if there's one still waiting to run
104           next if qsearch( 'queue', { 'job'     => 'FS::cust_main::queued_bill',
105                                       'custnum' => $custnum,
106                                       'status'  => 'new',
107                                     }
108                          );
109
110           #add job to queue that calls bill_and_collect with options
111           my $queue = new FS::queue {
112             'job'      => 'FS::cust_main::queued_bill',
113             'secure'   => 'Y',
114             'priority' => 99, #don't get in the way of provisioning jobs
115           };
116           my $error = $queue->insert( 'custnum'=>$custnum, %args );
117
118         }
119
120       } else {
121
122         my $cust_main = qsearchs( 'cust_main', { 'custnum' => $custnum } );
123         $cust_main->bill_and_collect( %args, 'debug' => $debug );
124
125       }
126
127     }
128
129     last if driver_name =~ /^mysql/;
130
131   }
132
133   $cursor_dbh->commit or die $cursor_dbh->errstr;
134
135 }
136
137 # freeside-daily %opt:
138 #  -d: Pretend it's 'date'.  Date is in any format Date::Parse is happy with,
139 #      but be careful.
140 #
141 #  -y: In addition to -d, which specifies an absolute date, the -y switch
142 #      specifies an offset, in days.  For example, "-y 15" would increment the
143 #      "pretend date" 15 days from whatever was specified by the -d switch
144 #      (or now, if no -d switch was given).
145 #
146 #  -n: When used with "-d" and/or "-y", specifies that invoices should be dated
147 #      with today's date, irregardless of the pretend date used to pre-generate
148 #      the invoices.
149 #
150 #  -p: Only process customers with the specified payby (I<CARD>, I<DCRD>, I<CHEK>, I<DCHK>, I<BILL>, I<COMP>, I<LECB>)
151 #
152 #  -a: Only process customers with the specified agentnum
153 #
154 #  -v: enable debugging
155 #
156 #  -l: debugging level
157
158 sub bill_where {
159   my( %opt ) = @_;
160
161   my $time = $opt{'time'};
162   my $invoice_time = $opt{'invoice_time'};
163
164   my $check_freq = $opt{'check_freq'} || '1d';
165
166   my @search = ();
167
168   push @search, "( cust_main.archived != 'Y' OR archived IS NULL )"; #disable?
169
170   push @search, "cust_main.payby    = '". $opt{'p'}. "'"
171     if $opt{'p'};
172   push @search, "cust_main.agentnum IN ( ". $opt{'a'}. " ) "
173     if $opt{'a'};
174
175   #it would be useful if i recognized $opt{g} / $not_pkgpart...
176
177   if ( @ARGV ) {
178     push @search, "( ".
179       join(' OR ', map "cust_main.custnum = $_", @ARGV ).
180     " )";
181   }
182
183   ###
184   # generate where_pkg/where_event search clause
185   ###
186
187   # select * from cust_main where
188   my $where_pkg = <<"END";
189     EXISTS(
190       SELECT 1 FROM cust_pkg
191         WHERE cust_main.custnum = cust_pkg.custnum
192           AND ( cancel IS NULL OR cancel = 0 )
193           AND (    ( ( setup IS NULL OR setup =  0 )
194                      AND ( start_date IS NULL OR start_date = 0
195                            OR ( start_date IS NOT NULL AND start_date <= $^T )
196                          )
197                    )
198                 OR bill  IS NULL OR bill  <= $time 
199                 OR ( expire  IS NOT NULL AND expire  <= $^T )
200                 OR ( adjourn IS NOT NULL AND adjourn <= $^T )
201               )
202     )
203 END
204
205   #some false laziness w/cust_main::Billing due_cust_event
206   my $where_event = join(' OR ', map {
207     my $eventtable = $_;
208
209     my $join  = FS::part_event_condition->join_conditions_sql(  $eventtable );
210     my $where = FS::part_event_condition->where_conditions_sql( $eventtable,
211                                                                 'time'=>$time,
212                                                               );
213     $where = $where ? "AND $where" : '';
214
215     my $are_part_event = 
216       "EXISTS ( SELECT 1 FROM part_event $join
217                   WHERE check_freq = '$check_freq'
218                     AND eventtable = '$eventtable'
219                     AND ( disabled = '' OR disabled IS NULL )
220                     $where
221               )
222       ";
223
224     if ( $eventtable eq 'cust_main' ) { 
225       $are_part_event;
226     } else {
227       "EXISTS ( SELECT 1 FROM $eventtable
228                   WHERE cust_main.custnum = $eventtable.custnum
229                     AND $are_part_event
230               )
231       ";
232     }
233
234   } FS::part_event->eventtables);
235
236   push @search, "( $where_pkg OR $where_event )";
237
238   warn "searching for customers:\n". join("\n", @search). "\n"
239     if $opt{'v'} || $opt{'l'};
240
241   join(' AND ', @search);
242
243 }
244
245 1;