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