declare new $opt_a
[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                     - ( select sum(amount) from cust_bill_pay
47                           where cust_bill.invnum = cust_bill_pay.invnum )
48                     - ( select sum(amount) from cust_credit_bill
49                           where cust_bill.invnum = cust_credit_bill.invnum )
50             and 0 < ( select count(*) from part_bill_event
51                         where payby = cust_main.payby
52                           and ( disabled is null or disabled = '' )
53                           and seconds <= $time - cust_bill._date
54                           and 0 = ( select count(*) from cust_bill_event
55                                      where cust_bill.invnum = cust_bill_event.invnum
56                                        and part_bill_event.eventpart = cust_bill_event.eventpart
57                                        and status = 'done'
58                                   )
59
60                     )
61       )
62 END
63
64 my $extra_sql = ( scalar(%search) ? ' AND ' : ' WHERE ' ). "$where_pkg OR $where_bill_event";
65
66 my @cust_main;
67 if ( @ARGV ) {
68   @cust_main = map { qsearchs('cust_main', { custnum => $_, %search } ) } @ARGV
69 } else {
70   @cust_main = qsearch('cust_main', \%search, '', $extra_sql );
71 }
72 ;
73
74 my($cust_main,%saw);
75 foreach $cust_main ( @cust_main ) {
76
77   # $^T not $time because -d is for pre-printing invoices
78   foreach my $cust_pkg (
79     grep { $_->expire && $_->expire <= $^T } $cust_main->ncancelled_pkgs
80   ) {
81     my $error = $cust_pkg->cancel;
82     warn "Error cancelling expired pkg ". $cust_pkg->pkgnum. " for custnum ".
83          $cust_main->custnum. ": $error"
84       if $error;
85   }
86
87   my $error = $cust_main->bill( 'time'    => $time,
88                                 'resetup' => $opt_s, );
89   warn "Error billing, custnum ". $cust_main->custnum. ": $error" if $error;
90
91   $cust_main->apply_payments;
92   $cust_main->apply_credits;
93
94   $error = $cust_main->collect( 'invoice_time' => $time );
95   warn "Error collecting, custnum". $cust_main->custnum. ": $error" if $error;
96
97 }
98
99 if ( driver_name eq 'Pg' ) {
100   dbh->{AutoCommit} = 1; #so we can vacuum
101   foreach my $table ( dbdef->tables ) {
102     my $sth = dbh->prepare("VACUUM ANALYZE $table") or die dbh->errstr;
103     $sth->execute or die $sth->errstr;
104   }
105 }
106
107 my $conf = new FS::Conf;
108 my $dest = $conf->config('dump-scpdest');
109 if ( $dest ) {
110   datasrc =~ /dbname=([\w\.]+)$/ or die "unparsable datasrc ". datasrc;
111   my $database = $1;
112   eval "use Net::SCP qw(scp);";
113   if ( driver_name eq 'Pg' ) {
114     system("pg_dump $database >/var/tmp/$database.sql")
115   } else {
116     die "database dumps not yet supported for ". driver_name;
117   }
118   if ( $conf->config('dump-pgpid') ) {
119     eval 'use GnuPG';
120     my $gpg = new GnuPG;
121     $gpg->encrypt( plaintext => "/var/tmp/$database.sql",
122                    output    => "/var/tmp/$database.gpg",
123                    recipient => $conf->config('dump-pgpid'),
124                  );
125     chmod 0600, '/var/tmp/$database.gpg';
126     scp("/var/tmp/$database.gpg", $dest);
127     unlink "/var/tmp/$database.gpg" or die $!;
128   } else {
129     chmod 0600, '/var/tmp/$database.sql';
130     scp("/var/tmp/$database.sql", $dest);
131   }
132   unlink "/var/tmp/$database.sql" or die $!;
133 }
134
135 # subroutines
136
137 sub untaint_argv {
138   foreach $_ ( $[ .. $#ARGV ) { #untaint @ARGV
139     #$ARGV[$_] =~ /^([\w\-\/]*)$/ || die "Illegal arguement \"$ARGV[$_]\"";
140     # Date::Parse
141     $ARGV[$_] =~ /^(.*)$/ || die "Illegal arguement \"$ARGV[$_]\"";
142     $ARGV[$_]=$1;
143   }
144 }
145
146 sub usage {
147   die "Usage:\n\n  freeside-daily [ -d 'date' ] user [ custnum custnum ... ]\n";
148 }
149
150 =head1 NAME
151
152 freeside-daily - Run daily billing and invoice collection events.
153
154 =head1 SYNOPSIS
155
156   freeside-daily [ -d 'date' ] [ -y days ] [ -p 'payby' ] [ -a agentnum ] [ -s ] [ -v ] user [ custnum custnum ... ]
157
158 =head1 DESCRIPTION
159
160 Bills customers and runs invoice collection events.  Should be run from
161 crontab daily.
162
163 This script replaces freeside-bill from 1.3.1.
164
165 Bills customers.  Searches for customers who are due for billing and calls
166 the bill and collect methods of a cust_main object.  See L<FS::cust_main>.
167
168   -d: Pretend it's 'date'.  Date is in any format Date::Parse is happy with,
169       but be careful.
170
171   -y: In addition to -d, which specifies an absolute date, the -y switch
172       specifies an offset, in days.  For example, "-y 15" would increment the
173       "pretend date" 15 days from whatever was specified by the -d switch
174       (or now, if no -d switch was given).
175
176   -p: Only process customers with the specified payby (I<CARD>, I<DCRD>, I<CHEK>, I<DCHK>, I<BILL>, I<COMP>, I<LECB>)
177
178   -a: Only process customers with the specified agentnum
179
180   -s: re-charge setup fees
181
182   -v: enable debugging
183
184 user: From the mapsecrets file - see config.html from the base documentation
185
186 custnum: if one or more customer numbers are specified, only bills those
187 customers.  Otherwise, bills all customers.
188
189 =head1 BUGS
190
191 =head1 SEE ALSO
192
193 L<FS::cust_main>, config.html from the base documentation
194
195 =cut
196