fix signup_server-realtime
[freeside.git] / fs_signup / fs_signup_server
1 #!/usr/bin/perl -Tw
2 #
3 # fs_signup_server
4 #
5
6 use strict;
7 use vars qw($pid);
8 use IO::Handle;
9 use Storable qw(nstore_fd fd_retrieve);
10 use Tie::RefHash;
11 use Net::SSH qw(sshopen2);
12 use FS::UID qw(adminsuidsetup);
13 use FS::Conf;
14 use FS::Record qw( qsearch qsearchs );
15 use FS::cust_main_county;
16 use FS::cust_main;
17 use FS::Msgcat qw(gettext);
18
19 use vars qw( $opt $Debug );
20
21 $Debug = 2;
22
23 my $user = shift or die &usage;
24 &adminsuidsetup( $user ); 
25
26 my $conf = new FS::Conf;
27
28 #my @payby = qw(CARD PREPAY);
29 my @payby = $conf->config('signup_server-payby');
30 my $smtpmachine = $conf->config('smtpmachine');
31
32 my $machine = shift or die &usage;
33
34 my $agentnum = shift or die &usage;
35 my $agent = qsearchs( 'agent', { 'agentnum' => $agentnum } ) or die &usage;
36 my $pkgpart_href = $agent->pkgpart_hashref;
37
38 my $refnum = shift or die &usage;
39
40 #causing trouble for some folks
41 #$SIG{CHLD} = sub { wait() };
42
43 $SIG{HUP} = \&killssh;
44 $SIG{INT} = \&killssh;
45 $SIG{QUIT} = \&killssh;
46 $SIG{TERM} = \&killssh;
47 $SIG{PIPE} = \&killssh;
48 sub killssh { kill 'TERM', $pid if $pid; exit; };
49
50 my($fs_signupd)="/usr/local/sbin/fs_signupd";
51
52 while (1) {
53   my($reader,$writer)=(new IO::Handle, new IO::Handle);
54   #seems to be broken - calling ->flush explicitly# $writer->autoflush(1);
55   warn "[fs_signup_server] Connecting to $machine...\n" if $Debug;
56   $pid = sshopen2($machine,$reader,$writer,$fs_signupd);
57
58   my @pops = qsearch('svc_acct_pop',{} );
59   my $init_data = {
60
61     #'_protocol' => 'signup',
62     #'_version' => '0.1',
63     #'_packet' => 'init'
64   
65     'cust_main_county' =>
66       [ map { $_->hashref } qsearch('cust_main_county', {}) ],
67       
68     'part_pkg' =>
69       [
70         map { $_->hashref }
71           grep { $_->svcpart('svc_acct') && $pkgpart_href->{ $_->pkgpart } }
72             qsearch( 'part_pkg', { 'disabled' => '' } )
73       ],
74
75     'svc_acct_pop' => [ map { $_->hashref } @pops ],
76
77     'security_phrase' => $conf->exists('security_phrase'),
78
79     'payby' => [ $conf->config('signup_server-payby') ],
80
81     'msgcat' => { map { $_=>gettext($_) } qw(
82       passwords_dont_match invalid_card unknown_card_type not_a
83     ) }
84
85   };
86
87   warn "[fs_signup_server] Sending init data...\n" if $Debug;
88   nstore_fd($init_data, $writer) or die "can't send init data: $!";
89   $writer->flush;
90
91   warn "[fs_signup_server] Entering main loop...\n" if $Debug;
92   while (1) {
93     warn "[fs_signup_server] Reading (waiting for) signup data...\n" if $Debug;
94     my $signup_data = fd_retrieve($reader);
95
96     if ( $Debug > 1 ) {
97       warn join('',
98         map { "  $_ => ". $signup_data->{$_}. "\n" } keys %$signup_data );
99     }
100
101     warn "[fs_signup_server] Processing signup...\n" if $Debug;
102
103     my $error = '';
104
105     #things that aren't necessary in base class, but are for signup server
106       #return "Passwords don't match"
107       #  if $hashref->{'_password'} ne $hashref->{'_password2'}
108     $error ||= gettext('empty_password') unless $signup_data->{'_password'};
109     $error ||= gettext('no_access_number_selected')
110       unless $signup_data->{'popnum'} || !scalar(@pops);
111
112     #shares some stuff with htdocs/edit/process/cust_main.cgi... take any
113     # common that are still here and library them.
114     my $cust_main = new FS::cust_main ( {
115       #'custnum'          => '',
116       'agentnum'         => $signup_data->{agentnum} || $agentnum,
117       'refnum'           => $refnum,
118
119       map { $_ => $signup_data->{$_} } qw(
120         last first ss company address1 address2 city county state zip country
121         daytime night fax payby payinfo paydate payname referral_custnum
122       ),
123
124     } );
125
126     $error ||= "Illegal payment type"
127       unless grep { $_ eq $signup_data->{'payby'} } @payby;
128
129     my @invoicing_list = split( /\s*\,\s*/, $signup_data->{'invoicing_list'} );
130
131     my $part_pkg =
132       qsearchs( 'part_pkg', { 'pkgpart' => $signup_data->{'pkgpart'} } )
133         or $error ||= "WARNING: unknown pkgpart ". $signup_data->{pkgpart};
134     my $svcpart = $part_pkg->svcpart unless $error;
135
136     # this should wind up in FS::cust_pkg!
137     my $agent = qsearchs( 'agent', { 'agentnum' => $agentnum } );
138     #my $pkgpart_href = $agent->pkgpart_hashref;
139     $error ||= "WARNING: agent $agentnum can't purchase pkgpart ".
140                $signup_data->{pkgpart}
141       unless $pkgpart_href->{ $signup_data->{pkgpart} };
142
143     my $cust_pkg = new FS::cust_pkg ( {
144       #later#'custnum' => $custnum,
145       'pkgpart' => $signup_data->{'pkgpart'},
146     } );
147     $error ||= $cust_pkg->check;
148
149     my $svc_acct = new FS::svc_acct ( {
150       'svcpart'   => $svcpart,
151       map { $_ => $signup_data->{$_} }
152         qw( username _password sec_phrase popnum ),
153     } );
154
155     my $y = $svc_acct->setdefault; # arguably should be in new method
156     $error ||= $y unless ref($y);
157
158     $error ||= $svc_acct->check;
159
160     use Tie::RefHash;
161     tie my %hash, 'Tie::RefHash';
162     %hash = ( $cust_pkg => [ $svc_acct ] );
163     $error ||= $cust_main->insert( \%hash, \@invoicing_list ); #msgcat
164
165     warn "[fs_signup_server] Sending results...\n" if $Debug;
166     print $writer $error, "\n";
167
168     if ( $conf->exists('signup_server-realtime') ) {
169       
170       my $bill_error = $cust_main->bill;
171       warn "[fs_signup_server] error billing new customer: $bill_error"
172         if $bill_error;
173
174       $cust_main->apply_payments;
175       $cust_main->apply_credits;
176
177       $bill_error = $cust_main->collect;
178       warn "[fs_signup_server] error collecting from new customer: $bill_error"
179         if $bill_error;
180
181       if ( $cust_main->balance ) {
182         #should check list for errors...
183         $cust_main->suspend;
184       }
185     }
186
187     if ( $error && $conf->config('signup_server-email') ) {
188       warn "[fs_signup_server] Sending email...\n" if $Debug;
189
190       #false laziness w/FS::cust_bill::send & FS::cust_pay::delete
191       use Mail::Header;
192       use Mail::Internet;
193       use Date::Format;
194       my $from = $conf->config('invoice_from'); #??? as good as any
195       $ENV{MAILADDRESS} = $from;
196       my $header = new Mail::Header ( [
197         "From: $from",
198         "To: ". $conf->config('signup_server-email'),
199         "Sender: $from",
200         "Reply-To: $from",
201         "Date: ". time2str("%a, %d %b %Y %X %z", time),
202         "Subject: FREESIDE NOTIFICATION: Signup Server",
203       ] );
204       my $body = [
205         "This is an automatic message from your Freeside installation\n",
206         "informing you a customer has signed up via the signup server:\n",
207         "\n",
208         'custnum: '. $cust_main->custnum. "\n",
209         'Name   : '. $cust_main->last. ", ". $cust_main->first. "\n",
210         'Agent  : '. $cust_main->agent->agent. "\n",
211         "\n",
212       ];
213       if ( $cust_main->balance ) {
214         push @$body,
215           "This customer has an outstanding balance and has been suspended.\n";
216       }
217       my $message = new Mail::Internet ( 'Header' => $header, 'Body' => $body );
218       $!=0;
219       $message->smtpsend( Host => $smtpmachine )
220         or $message->smtpsend( Host => $smtpmachine, Debug => 1 )
221           or warn "[fs_signup_server] can't send email to ".
222                    $conf->config('signup_server-email').
223                    " via server $smtpmachine with SMTP: $!";
224       #end-of-send mail
225     }
226
227   }
228   close $writer;
229   close $reader;
230   warn "connection to $machine lost!  waiting 60 seconds...\n";
231   sleep 60;
232   warn "reconnecting...\n";
233 }
234
235 sub usage {
236   die "Usage:\n\n  fs_signup_server user machine agentnum refnum\n";
237 }
238