add prepaid support which sets RADIUS Expiration attribute, update customer view...
[freeside.git] / FS / bin / freeside-daily
1 #!/usr/bin/perl -w
2
3 use strict;
4 use Fcntl qw(:flock);
5 use Date::Parse;
6 use Getopt::Std;
7 use FS::UID qw(adminsuidsetup driver_name dbh datasrc);
8 use FS::Record qw(qsearch qsearchs dbdef);
9 use FS::Conf;
10 use FS::cust_main;
11
12 &untaint_argv;  #what it sounds like  (eww)
13 use vars qw($opt_d $opt_v $opt_p $opt_a $opt_s $opt_y);
14 getopts("p:a:d:vsy:");
15 my $user = shift or die &usage;
16
17 adminsuidsetup $user;
18
19 $FS::cust_main::DEBUG = 1 if $opt_v;
20
21 my %search = ();
22 $search{'payby'}    = $opt_p if $opt_p;
23 $search{'agentnum'} = $opt_a if $opt_a;
24
25 #we're at now now (and later).
26 my($time)= $opt_d ? str2time($opt_d) : $^T;
27 $time += $opt_y * 86400 if $opt_y;
28
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 )
37                 )
38       )
39 END
40
41 # or
42 my $where_bill_event = <<"END";
43   0 < ( select count(*) from cust_bill
44           where cust_main.custnum = cust_bill.custnum
45             and 0 < charged
46                     - coalesce(
47                                 ( select sum(amount) from cust_bill_pay
48                                     where cust_bill.invnum = cust_bill_pay.invnum )
49                                 ,0
50                               )
51                     - coalesce(
52                                 ( select sum(amount) from cust_credit_bill
53                                     where cust_bill.invnum = cust_credit_bill.invnum )
54                                 ,0
55                               )
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
63                                        and status = 'done'
64                                   )
65
66                     )
67       )
68 END
69
70 my $extra_sql = ( scalar(%search) ? ' AND ' : ' WHERE ' ). "( $where_pkg OR $where_bill_event )";
71
72 my @cust_main;
73 if ( @ARGV ) {
74   @cust_main = map { qsearchs('cust_main', { custnum => $_, %search } ) } @ARGV
75 } else {
76   @cust_main = qsearch('cust_main', \%search, '', $extra_sql );
77 }
78 ;
79
80 my($cust_main,%saw);
81 foreach $cust_main ( @cust_main ) {
82
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
86   ) {
87     my $error = $cust_pkg->cancel;
88     warn "Error cancelling expired pkg ". $cust_pkg->pkgnum. " for custnum ".
89          $cust_main->custnum. ": $error"
90       if $error;
91   }
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
96          }
97          $cust_main->ncancelled_pkgs
98   ) {
99     my $error = $cust_pkg->suspend;
100     warn "Error suspending package ". $cust_pkg->pkgnum.
101          " for custnum ". $cust_main->custnum.
102          ": $error"
103       if $error;
104   }
105
106   my $error = $cust_main->bill( 'time'    => $time,
107                                 'resetup' => $opt_s, );
108   warn "Error billing, custnum ". $cust_main->custnum. ": $error" if $error;
109
110   $cust_main->apply_payments;
111   $cust_main->apply_credits;
112
113   $error = $cust_main->collect( 'invoice_time' => $time );
114   warn "Error collecting, custnum". $cust_main->custnum. ": $error" if $error;
115
116 }
117
118 if ( driver_name eq 'Pg' ) {
119   dbh->{AutoCommit} = 1; #so we can vacuum
120   foreach my $table ( dbdef->tables ) {
121     my $sth = dbh->prepare("VACUUM ANALYZE $table") or die dbh->errstr;
122     $sth->execute or die $sth->errstr;
123   }
124 }
125
126 my $conf = new FS::Conf;
127 my $dest = $conf->config('dump-scpdest');
128 if ( $dest ) {
129   datasrc =~ /dbname=([\w\.]+)$/ or die "unparsable datasrc ". datasrc;
130   my $database = $1;
131   eval "use Net::SCP qw(scp);";
132   if ( driver_name eq 'Pg' ) {
133     system("pg_dump $database >/var/tmp/$database.sql")
134   } else {
135     die "database dumps not yet supported for ". driver_name;
136   }
137   if ( $conf->config('dump-pgpid') ) {
138     eval 'use GnuPG';
139     my $gpg = new GnuPG;
140     $gpg->encrypt( plaintext => "/var/tmp/$database.sql",
141                    output    => "/var/tmp/$database.gpg",
142                    recipient => $conf->config('dump-pgpid'),
143                  );
144     chmod 0600, '/var/tmp/$database.gpg';
145     scp("/var/tmp/$database.gpg", $dest);
146     unlink "/var/tmp/$database.gpg" or die $!;
147   } else {
148     chmod 0600, '/var/tmp/$database.sql';
149     scp("/var/tmp/$database.sql", $dest);
150   }
151   unlink "/var/tmp/$database.sql" or die $!;
152 }
153
154 # subroutines
155
156 sub untaint_argv {
157   foreach $_ ( $[ .. $#ARGV ) { #untaint @ARGV
158     #$ARGV[$_] =~ /^([\w\-\/]*)$/ || die "Illegal arguement \"$ARGV[$_]\"";
159     # Date::Parse
160     $ARGV[$_] =~ /^(.*)$/ || die "Illegal arguement \"$ARGV[$_]\"";
161     $ARGV[$_]=$1;
162   }
163 }
164
165 sub usage {
166   die "Usage:\n\n  freeside-daily [ -d 'date' ] user [ custnum custnum ... ]\n";
167 }
168
169 =head1 NAME
170
171 freeside-daily - Run daily billing and invoice collection events.
172
173 =head1 SYNOPSIS
174
175   freeside-daily [ -d 'date' ] [ -y days ] [ -p 'payby' ] [ -a agentnum ] [ -s ] [ -v ] user [ custnum custnum ... ]
176
177 =head1 DESCRIPTION
178
179 Bills customers and runs invoice collection events.  Should be run from
180 crontab daily.
181
182 This script replaces freeside-bill from 1.3.1.
183
184 Bills customers.  Searches for customers who are due for billing and calls
185 the bill and collect methods of a cust_main object.  See L<FS::cust_main>.
186
187   -d: Pretend it's 'date'.  Date is in any format Date::Parse is happy with,
188       but be careful.
189
190   -y: In addition to -d, which specifies an absolute date, the -y switch
191       specifies an offset, in days.  For example, "-y 15" would increment the
192       "pretend date" 15 days from whatever was specified by the -d switch
193       (or now, if no -d switch was given).
194
195   -p: Only process customers with the specified payby (I<CARD>, I<DCRD>, I<CHEK>, I<DCHK>, I<BILL>, I<COMP>, I<LECB>)
196
197   -a: Only process customers with the specified agentnum
198
199   -s: re-charge setup fees
200
201   -v: enable debugging
202
203 user: From the mapsecrets file - see config.html from the base documentation
204
205 custnum: if one or more customer numbers are specified, only bills those
206 customers.  Otherwise, bills all customers.
207
208 =head1 BUGS
209
210 =head1 SEE ALSO
211
212 L<FS::cust_main>, config.html from the base documentation
213
214 =cut
215