ac211ec278f09afbe135076e679c2218d8bb2ae6
[freeside.git] / FS / FS / ClientAPI / Signup.pm
1 package FS::ClientAPI::Signup;
2
3 use strict;
4 use Tie::RefHash;
5 use FS::Conf;
6 use FS::Record qw(qsearch qsearchs dbdef);
7 use FS::Msgcat qw(gettext);
8 use FS::Misc qw(card_types);
9 use FS::ClientAPI_SessionCache;
10 use FS::agent;
11 use FS::cust_main_county;
12 use FS::part_pkg;
13 use FS::svc_acct_pop;
14 use FS::cust_main;
15 use FS::cust_pkg;
16 use FS::svc_acct;
17 use FS::acct_snarf;
18 use FS::queue;
19 use FS::reg_code;
20
21 sub signup_info {
22   my $packet = shift;
23
24   my $conf = new FS::Conf;
25
26   use vars qw($signup_info_cache); #cache for performance;
27   $signup_info_cache ||= {
28     'cust_main_county' =>
29       [ map { $_->hashref } qsearch('cust_main_county', {}) ],
30
31     'agent' =>
32       [
33         map { $_->hashref }
34           qsearch('agent', { 'disabled' => '' } )
35       ],
36
37     'part_referral' =>
38       [
39         map { $_->hashref }
40           qsearch('part_referral', { 'disabled' => '' })
41       ],
42
43     'agentnum2part_pkg' =>
44       {
45         map {
46           my $href = $_->pkgpart_hashref;
47           $_->agentnum =>
48             [
49               map { { 'payby'       => [ $_->payby ],
50                       'freq_pretty' => $_->freq_pretty,
51                       'options'     => { $_->options },
52                       %{$_->hashref}
53                   } }
54                 grep { $_->svcpart('svc_acct') && $href->{ $_->pkgpart } }
55                   qsearch( 'part_pkg', { 'disabled' => '' } )
56             ];
57         } qsearch('agent', { 'disabled' => '' })
58       },
59
60     'svc_acct_pop' => [ map { $_->hashref } qsearch('svc_acct_pop',{} ) ],
61
62     'emailinvoiceonly' => $conf->exists('emailinvoiceonly'),
63
64     'security_phrase' => $conf->exists('security_phrase'),
65
66     'payby' => [ $conf->config('signup_server-payby') ],
67
68     'card_types' => card_types(),
69
70     'cvv_enabled' => defined dbdef->table('cust_main')->column('paycvv'), # 1,
71
72     'ship_enabled' => defined dbdef->table('cust_main')->column('ship_last'),#1,
73
74     'msgcat' => { map { $_=>gettext($_) } qw(
75       passwords_dont_match invalid_card unknown_card_type not_a empty_password illegal_or_empty_text
76     ) },
77
78     'statedefault' => $conf->config('statedefault') || 'CA',
79
80     'countrydefault' => $conf->config('countrydefault') || 'US',
81
82     'refnum' => $conf->config('signup_server-default_refnum'),
83
84     'default_pkgpart' => $conf->config('signup_server-default_pkgpart'),
85
86   };
87
88   my $signup_info = { %$signup_info_cache };
89
90   my @addl = qw( signup_server-classnum2 signup_server-classnum3 );
91
92   if ( grep { $conf->exists($_) } @addl ) {
93   
94     $signup_info->{optional_packages} = [];
95
96     foreach my $addl ( @addl ) {
97       my $classnum = $conf->config($addl) or next;
98
99       my @pkgs = map { {
100                          'freq_pretty' => $_->freq_pretty,
101                          'options'     => { $_->options },
102                          %{ $_->hashref }
103                        };
104                      }
105                      qsearch( 'part_pkg', { classnum => $classnum } );
106
107       push @{$signup_info->{optional_packages}}, \@pkgs;
108
109     }
110
111   }
112
113   my $agentnum = $packet->{'agentnum'}
114                  || $conf->config('signup_server-default_agentnum');
115   $agentnum =~ /^(\d*)$/ or die "illegal agentnum";
116   $agentnum = $1;
117
118   my $session = '';
119   if ( exists $packet->{'session_id'} ) {
120     my $cache = new FS::ClientAPI_SessionCache( {
121       'namespace' => 'FS::ClientAPI::Agent',
122     } );
123     $session = $cache->get($packet->{'session_id'});
124     if ( $session ) {
125       $agentnum = $session->{'agentnum'};
126     } else {
127       return { 'error' => "Can't resume session" }; #better error message
128     }
129   }elsif( exists $packet->{'customer_session_id'} ) {
130     my $cache = new FS::ClientAPI_SessionCache( {
131       'namespace' => 'FS::ClientAPI::MyAccount',
132     } );
133     $session = $cache->get($packet->{'customer_session_id'});
134     if ( $session ) {
135       my $custnum = $session->{'custnum'};
136       my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum });
137       return { 'error' => "Can't find your customer record" } unless $cust_main;
138       $agentnum = $cust_main->agentnum;
139     } else {
140       return { 'error' => "Can't resume session" }; #better error message
141     }
142   }
143
144   $signup_info->{'part_pkg'} = [];
145
146   if ( $packet->{'reg_code'} ) {
147     $signup_info->{'part_pkg'} = 
148       [ map { { 'payby'       => [ $_->payby ],
149                 'freq_pretty' => $_->freq_pretty,
150                 'options'     => { $_->options },
151                 %{$_->hashref}
152               };
153             }
154           grep { $_->svcpart('svc_acct') }
155           map { $_->part_pkg }
156             qsearchs( 'reg_code', { 'code'     => $packet->{'reg_code'},
157                                     'agentnum' => $agentnum,              } )
158
159       ];
160
161     $signup_info->{'error'} = 'Unknown registration code'
162       unless @{ $signup_info->{'part_pkg'} };
163
164   } elsif ( $packet->{'promo_code'} ) {
165
166     $signup_info->{'part_pkg'} =
167       [ map { { 'payby'   => [ $_->payby ],
168                 'freq_pretty' => $_->freq_pretty,
169                 'options'     => { $_->options },
170                 %{$_->hashref}
171             } }
172           grep { $_->svcpart('svc_acct') }
173             qsearch( 'part_pkg', { 'promo_code' => {
174                                      op=>'ILIKE',
175                                      value=>$packet->{'promo_code'}
176                                    },
177                                    'disabled'   => '',                  } )
178       ];
179
180     $signup_info->{'error'} = 'Unknown promotional code'
181       unless @{ $signup_info->{'part_pkg'} };
182   }
183
184   if ( $agentnum && ! @{ $signup_info->{'part_pkg'} } ) {
185     $signup_info->{'part_pkg'} = $signup_info->{'agentnum2part_pkg'}{$agentnum};
186
187     $signup_info->{'part_referral'} =
188       [
189         map { $_->hashref }
190           qsearch( {
191                      'table'     => 'part_referral',
192                      'hashref'   => { 'disabled' => '' },
193                      'extra_sql' => "AND (    agentnum = $agentnum  ".
194                                     "      OR agentnum IS NULL    ) ",
195                    },
196                  )
197       ];
198
199   }
200   # else {
201   # delete $signup_info->{'part_pkg'};
202   #}
203
204   $signup_info->{'part_pkg'} = [ sort { $a->{pkg} cmp $b->{pkg} }  # case?
205                                       @{ $signup_info->{'part_pkg'} }
206                                ];
207
208   if ( exists $packet->{'session_id'} ) {
209     my $agent_signup_info = { %$signup_info };
210     delete $agent_signup_info->{agentnum2part_pkg};
211     $agent_signup_info->{'agent'} = $session->{'agent'};
212     $agent_signup_info;
213   } else {
214     $signup_info;
215   }
216
217 }
218
219 sub new_customer {
220   my $packet = shift;
221
222   my $conf = new FS::Conf;
223   
224   #things that aren't necessary in base class, but are for signup server
225     #return "Passwords don't match"
226     #  if $hashref->{'_password'} ne $hashref->{'_password2'}
227   return { 'error' => gettext('empty_password') }
228     unless length($packet->{'_password'});
229   # a bit inefficient for large numbers of pops
230   return { 'error' => gettext('no_access_number_selected') }
231     unless $packet->{'popnum'} || !scalar(qsearch('svc_acct_pop',{} ));
232
233   my $agentnum;
234   if ( exists $packet->{'session_id'} ) {
235     my $cache = new FS::ClientAPI_SessionCache( {
236       'namespace' => 'FS::ClientAPI::Agent',
237     } );
238     my $session = $cache->get($packet->{'session_id'});
239     if ( $session ) {
240       $agentnum = $session->{'agentnum'};
241     } else {
242       return { 'error' => "Can't resume session" }; #better error message
243     }
244   } else {
245     $agentnum = $packet->{agentnum}
246                 || $conf->config('signup_server-default_agentnum');
247   }
248
249   #shares some stuff with htdocs/edit/process/cust_main.cgi... take any
250   # common that are still here and library them.
251   my $cust_main = new FS::cust_main ( {
252     #'custnum'          => '',
253     'agentnum'      => $agentnum,
254     'refnum'        => $packet->{refnum}
255                        || $conf->config('signup_server-default_refnum'),
256
257     map { $_ => $packet->{$_} } qw(
258
259       last first ss company address1 address2
260       city county state zip country
261       daytime night fax
262
263       ship_last ship_first ship_ss ship_company ship_address1 ship_address2
264       ship_city ship_county ship_state ship_zip ship_country
265       ship_daytime ship_night ship_fax
266
267       payby
268       payinfo paycvv paydate payname
269       paystart_month paystart_year payissue
270       payip
271
272       referral_custnum comments
273     )
274
275   } );
276
277   return { 'error' => "Illegal payment type" }
278     unless grep { $_ eq $packet->{'payby'} }
279                 $conf->config('signup_server-payby');
280
281   $cust_main->payinfo($cust_main->daytime)
282     if $cust_main->payby eq 'LECB' && ! $cust_main->payinfo;
283
284   my @invoicing_list = $packet->{'invoicing_list'}
285                          ? split( /\s*\,\s*/, $packet->{'invoicing_list'} )
286                          : ();
287
288   $packet->{'pkgpart'} =~ /^(\d+)$/ or '' =~ /^()$/;
289   my $pkgpart = $1;
290   return { 'error' => 'Please select a package' } unless $pkgpart; #msgcat
291
292   my $part_pkg =
293     qsearchs( 'part_pkg', { 'pkgpart' => $pkgpart } )
294       or return { 'error' => "WARNING: unknown pkgpart: $pkgpart" };
295   my $svcpart = $part_pkg->svcpart('svc_acct');
296
297   my $reg_code = '';
298   if ( $packet->{'reg_code'} ) {
299     $reg_code = qsearchs( 'reg_code', { 'code'     => $packet->{'reg_code'},
300                                         'agentnum' => $agentnum,             } )
301       or return { 'error' => 'Unknown registration code' };
302   }
303
304   my $cust_pkg = new FS::cust_pkg ( {
305     #later#'custnum' => $custnum,
306     'pkgpart'    => $packet->{'pkgpart'},
307     'promo_code' => $packet->{'promo_code'},
308     'reg_code'   => $packet->{'reg_code'},
309   } );
310   #my $error = $cust_pkg->check;
311   #return { 'error' => $error } if $error;
312
313   my $svc_acct = new FS::svc_acct ( {
314     'svcpart'   => $svcpart,
315     map { $_ => $packet->{$_} }
316       qw( username _password sec_phrase popnum ),
317   } );
318
319   my @acct_snarf;
320   my $snarfnum = 1;
321   while (    exists($packet->{"snarf_machine$snarfnum"})
322           && length($packet->{"snarf_machine$snarfnum"}) ) {
323     my $acct_snarf = new FS::acct_snarf ( {
324       'machine'   => $packet->{"snarf_machine$snarfnum"},
325       'protocol'  => $packet->{"snarf_protocol$snarfnum"},
326       'username'  => $packet->{"snarf_username$snarfnum"},
327       '_password' => $packet->{"snarf_password$snarfnum"},
328     } );
329     $snarfnum++;
330     push @acct_snarf, $acct_snarf;
331   }
332   $svc_acct->child_objects( \@acct_snarf );
333
334   my $y = $svc_acct->setdefault; # arguably should be in new method
335   return { 'error' => $y } if $y && !ref($y);
336
337   #$error = $svc_acct->check;
338   #return { 'error' => $error } if $error;
339
340   #setup a job dependancy to delay provisioning
341   my $placeholder = new FS::queue ( {
342     'job'    => 'FS::ClientAPI::Signup::__placeholder',
343     'status' => 'locked',
344   } );
345   my $error = $placeholder->insert;
346   return { 'error' => $error } if $error;
347
348   use Tie::RefHash;
349   tie my %hash, 'Tie::RefHash';
350   %hash = ( $cust_pkg => [ $svc_acct ] );
351   #msgcat
352   $error = $cust_main->insert(
353     \%hash,
354     \@invoicing_list,
355     'depend_jobnum' => $placeholder->jobnum,
356   );
357   if ( $error ) {
358     my $perror = $placeholder->delete;
359     $error .= " (Additionally, error removing placeholder: $perror)" if $perror;
360     return { 'error' => $error };
361   }
362
363   if ( $conf->exists('signup_server-realtime') ) {
364
365     #warn "[fs_signup_server] Billing customer...\n" if $Debug;
366
367     my $bill_error = $cust_main->bill;
368     #warn "[fs_signup_server] error billing new customer: $bill_error"
369     #  if $bill_error;
370
371     $cust_main->apply_payments_and_credits;
372
373     $bill_error = $cust_main->collect('realtime' => 1);
374     #warn "[fs_signup_server] error collecting from new customer: $bill_error"
375     #  if $bill_error;
376
377     if ( $cust_main->balance > 0 ) {
378
379       #this makes sense.  credit is "un-doing" the invoice
380       $cust_main->credit( $cust_main->balance, 'signup server decline' );
381       $cust_main->apply_credits;
382
383       #should check list for errors...
384       #$cust_main->suspend;
385       local $FS::svc_Common::noexport_hack = 1;
386       $cust_main->cancel('quiet'=>1);
387
388       my $perror = $placeholder->depended_delete;
389       warn "error removing provisioning jobs after decline: $perror" if $perror;
390       unless ( $perror ) {
391         $perror = $placeholder->delete;
392         warn "error removing placeholder after decline: $perror" if $perror;
393       }
394
395       return { 'error' => '_decline' };
396     }
397
398   }
399
400   if ( $reg_code ) {
401     $error = $reg_code->delete;
402     return { 'error' => $error } if $error;
403   }
404
405   $error = $placeholder->delete;
406   return { 'error' => $error } if $error;
407
408   return { error => '' };
409
410 }
411
412 1;