create prospects through signup API, #39776
[freeside.git] / FS / FS / ClientAPI / Signup.pm
1 package FS::ClientAPI::Signup;
2
3 use strict;
4 use vars qw( $DEBUG $me );
5 use subs qw( _myaccount_cache );
6 use Data::Dumper;
7 use Tie::RefHash;
8 use Digest::SHA qw(sha512_hex);
9 use FS::Conf;
10 use FS::Record qw(qsearch qsearchs dbdef dbh);
11 use FS::CGI qw(popurl);
12 use FS::Msgcat qw(gettext);
13 use FS::Misc qw(card_types);
14 use FS::ClientAPI_SessionCache;
15 use FS::agent;
16 use FS::cust_main_county;
17 use FS::part_pkg;
18 use FS::svc_acct_pop;
19 use FS::cust_main;
20 use FS::cust_pkg;
21 use FS::svc_acct;
22 use FS::svc_phone;
23 use FS::acct_snarf;
24 use FS::queue;
25 use FS::reg_code;
26 use FS::payby;
27 use FS::banned_pay;
28 use FS::part_tag;
29
30 $DEBUG = 0;
31 $me = '[FS::ClientAPI::Signup]';
32
33 =head1 NAME
34
35 FS::ClientAPI::Signup - Front-end API for signing up customers
36
37 =head1 DESCRIPTION
38
39 This module provides the ClientAPI functions for talking to a signup
40 server. The signup server is open to the public, i.e. does not require a
41 login. The back-end Freeside server creates customers, orders packages and
42 services, and processes initial payments.
43
44 =head1 METHODS
45
46 =over 4
47
48 =cut
49
50 # document the rest of this as we work on it
51
52 sub clear_cache {
53   warn "$me clear_cache called\n" if $DEBUG;
54   my $cache = new FS::ClientAPI_SessionCache( {
55       'namespace' => 'FS::ClientAPI::Signup',
56   } );
57   $cache->clear();
58   return {};
59 }
60
61 sub signup_info {
62   my $packet = shift;
63
64   warn "$me signup_info called on $packet\n" if $DEBUG;
65
66   my $conf = new FS::Conf;
67   my $svc_x = $conf->config('signup_server-service') || 'svc_acct';
68
69   my $cache = new FS::ClientAPI_SessionCache( {
70     'namespace' => 'FS::ClientAPI::Signup',
71   } );
72   my $signup_info_cache = $cache->get('signup_info_cache');
73
74   if ( $signup_info_cache ) {
75
76     warn "$me loading cached signup info\n" if $DEBUG > 1;
77
78   } else {
79
80     warn "$me populating signup info cache\n" if $DEBUG > 1;
81
82     my $agentnum2part_pkg = 
83       {
84         map {
85           my $agent = $_;
86           my $href = $agent->pkgpart_hashref;
87           $agent->agentnum =>
88             [
89               map { { 'payby'       => [ $_->payby ],
90                       'freq_pretty' => $_->freq_pretty,
91                       'options'     => { $_->options },
92                       %{$_->hashref}
93                   } }
94                 grep { $_->svcpart($svc_x)
95                        && ( $href->{ $_->pkgpart }
96                             || ( $_->agentnum
97                                  && $_->agentnum == $agent->agentnum
98                                )
99                           )
100                      }
101                   qsearch( 'part_pkg', { 'disabled' => '' } )
102             ];
103         } qsearch('agent', { 'disabled' => '' })
104       };
105
106     my $msgcat = { map { $_=>gettext($_) }
107                        qw( passwords_dont_match invalid_card unknown_card_type
108                            not_a empty_password illegal_or_empty_text )
109                  };
110     warn "msgcat: ". Dumper($msgcat). "\n" if $DEBUG > 2;
111
112     my $label = { map { $_ => FS::Msgcat::_gettext($_) }
113                       qw( stateid stateid_state )
114                 };
115     warn "label: ". Dumper($label). "\n" if $DEBUG > 2;
116
117     my @agent_fields = qw( agentnum agent );
118
119     my @bools = qw( emailinvoiceonly security_phrase );
120
121     my @signup_bools = qw( no_company recommend_daytime recommend_email );
122
123     my @signup_server_scalars = qw( default_pkgpart default_svcpart default_domsvc );
124
125     my @selfservice_textareas = qw( head body_header body_footer );
126
127     my @selfservice_scalars = qw(
128       body_bgcolor box_bgcolor
129       text_color link_color vlink_color hlink_color alink_color
130       font title_color title_align title_size menu_bgcolor menu_fontsize
131     );
132
133     #XXX my @selfservice_bools = qw(
134     #  menu_skipblanks menu_skipheadings menu_nounderline
135     #);
136
137     #my $selfservice_binaries = qw(
138     #  title_left_image title_right_image
139     #  menu_top_image menu_body_image menu_bottom_image
140     #);
141
142     $signup_info_cache = {
143
144       'cust_main_county' => [ map $_->hashref,
145                                   qsearch('cust_main_county', {} )
146                             ],
147
148       'agent' => [ map { my $agent = $_;
149                          +{ map { $_ => $agent->get($_) } @agent_fields }
150                        }
151                        qsearch('agent', { 'disabled' => '' } )
152                  ],
153
154       'part_referral' => [ map $_->hashref,
155                                qsearch('part_referral', { 'disabled' => '' } )
156                          ],
157
158       'agentnum2part_pkg' => $agentnum2part_pkg,
159
160       'svc_acct_pop' => [ map $_->hashref, qsearch('svc_acct_pop',{} ) ],
161
162       'emailinvoiceonly' => $conf->exists('emailinvoiceonly'),
163
164       'security_phrase' => $conf->exists('security_phrase'),
165
166       'nomadix' => $conf->exists('signup_server-nomadix'),
167
168       'payby' => [ $conf->config('signup_server-payby') ],
169
170       'payby_longname' => [ map { FS::payby->longname($_) } 
171                             $conf->config('signup_server-payby') ],
172
173       'card_types' => card_types(),
174
175       ( map { $_ => $conf->exists("signup-$_") } @signup_bools ),
176
177       ( map { $_ => scalar($conf->config("signup_server-$_")) }
178             @signup_server_scalars
179       ),
180
181       ( map { $_ => join("\n", $conf->config("selfservice-$_")) }
182             @selfservice_textareas
183       ),
184       ( map { $_ => scalar($conf->config("selfservice-$_")) }
185             @selfservice_scalars
186       ),
187
188       #( map { $_ => scalar($conf->config_binary("selfservice-$_")) }
189       #      @selfservice_binaries
190       #),
191
192       'agentnum2part_pkg'  => $agentnum2part_pkg,
193       'svc_acct_pop'       => [ map $_->hashref, qsearch('svc_acct_pop',{} ) ],
194       'nomadix'            => $conf->exists('signup_server-nomadix'),
195       'payby'              => [ $conf->config('signup_server-payby') ],
196       'card_types'         => card_types(),
197       'paytypes'           => [ @FS::cust_main::paytypes ],
198       'cvv_enabled'        => 1,
199       'require_cvv'        => $conf->exists('signup-require_cvv'),
200       'stateid_enabled'    => $conf->exists('show_stateid'),
201       'paystate_enabled'   => $conf->exists('show_bankstate'),
202       'exempt_groups'      => [ grep /\S/, $conf->config('tax-cust_exempt-groups') ],
203       'ship_enabled'       => 1,
204       'msgcat'             => $msgcat,
205       'label'              => $label,
206       'statedefault'       => scalar($conf->config('statedefault')) || 'CA',
207       'countrydefault'     => scalar($conf->config('countrydefault')) || 'US',
208       'refnum'             => scalar($conf->config('signup_server-default_refnum')),
209       'signup_service'     => $svc_x,
210       'company_name'       => scalar($conf->config('company_name')),
211       #per-agent?
212       'logo'               => scalar($conf->config_binary('logo.png')),
213       'prepaid_template_custnum' => $conf->exists('signup_server-prepaid-template-custnum'),
214     };
215
216     $cache->set('signup_info_cache', $signup_info_cache);
217
218   }
219
220   my $signup_info = { %$signup_info_cache };
221   warn "$me signup info loaded\n" if $DEBUG > 1;
222   warn Dumper($signup_info). "\n" if $DEBUG > 2;
223
224   my @addl = qw( signup_server-classnum2 signup_server-classnum3 );
225
226   if ( grep { $conf->exists($_) } @addl ) {
227   
228     $signup_info->{optional_packages} = [];
229
230     foreach my $addl ( @addl ) {
231
232       warn "$me adding optional package info\n" if $DEBUG > 1;
233
234       my $classnum = $conf->config($addl) or next;
235
236       my @pkgs = map { {
237                          'freq_pretty' => $_->freq_pretty,
238                          'options'     => { $_->options },
239                          %{ $_->hashref }
240                        };
241                      }
242                      qsearch( 'part_pkg', { classnum => $classnum } );
243
244       push @{$signup_info->{optional_packages}}, \@pkgs;
245
246       warn "$me done adding opt. package info for $classnum\n" if $DEBUG > 1;
247
248     }
249
250   }
251
252   my $agentnum = $packet->{'agentnum'}
253                  || $conf->config('signup_server-default_agentnum');
254   $agentnum =~ /^(\d*)$/ or die "illegal agentnum";
255   $agentnum = $1;
256
257   my $session = '';
258   if ( exists $packet->{'session_id'} ) {
259
260     warn "$me loading agent session\n" if $DEBUG > 1;
261     my $cache = new FS::ClientAPI_SessionCache( {
262       'namespace' => 'FS::ClientAPI::Agent',
263     } );
264     $session = $cache->get($packet->{'session_id'});
265     if ( $session ) {
266       $agentnum = $session->{'agentnum'};
267     } else {
268       return { 'error' => "Can't resume session" }; #better error message
269     }
270     warn "$me done loading agent session\n" if $DEBUG > 1;
271
272   } elsif ( exists $packet->{'customer_session_id'} ) {
273
274     warn "$me loading customer session\n" if $DEBUG > 1;
275     my $cache = new FS::ClientAPI_SessionCache( {
276       'namespace' => 'FS::ClientAPI::MyAccount',
277     } );
278     $session = $cache->get($packet->{'customer_session_id'});
279     if ( $session ) {
280       my $custnum = $session->{'custnum'};
281       my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum });
282       return { 'error' => "Can't find your customer record" } unless $cust_main;
283       $agentnum = $cust_main->agentnum;
284     } else {
285       return { 'error' => "Can't resume session" }; #better error message
286     }
287     warn "$me done loading customer session\n" if $DEBUG > 1;
288
289   }
290
291   $signup_info->{'part_pkg'} = [];
292
293   if ( $packet->{'reg_code'} ) {
294
295     warn "$me setting package list via reg_code\n" if $DEBUG > 1;
296
297     $signup_info->{'part_pkg'} = 
298       [ map { { 'payby'       => [ $_->payby ],
299                 'freq_pretty' => $_->freq_pretty,
300                 'options'     => { $_->options },
301                 %{$_->hashref}
302               };
303             }
304           grep { $_->svcpart($svc_x) }
305           map { $_->part_pkg }
306             qsearchs( 'reg_code', { 'code'     => $packet->{'reg_code'},
307                                     'agentnum' => $agentnum,              } )
308
309       ];
310
311     $signup_info->{'error'} = 'Unknown registration code'
312       unless @{ $signup_info->{'part_pkg'} };
313
314     warn "$me done setting package list via reg_code\n" if $DEBUG > 1;
315
316   } elsif ( $packet->{'promo_code'} ) {
317
318     warn "$me setting package list via promo_code\n" if $DEBUG > 1;
319
320     $signup_info->{'part_pkg'} =
321       [ map { { 'payby'   => [ $_->payby ],
322                 'freq_pretty' => $_->freq_pretty,
323                 'options'     => { $_->options },
324                 %{$_->hashref}
325             } }
326           grep { $_->svcpart($svc_x) }
327             qsearch( 'part_pkg', { 'promo_code' => {
328                                      op=>'ILIKE',
329                                      value=>$packet->{'promo_code'}
330                                    },
331                                    'disabled'   => '',                  } )
332       ];
333
334     $signup_info->{'error'} = 'Unknown promotional code'
335       unless @{ $signup_info->{'part_pkg'} };
336
337     warn "$me done setting package list via promo_code\n" if $DEBUG > 1;
338   }
339
340   if ( $agentnum ) {
341
342     warn "$me setting agent-specific payment flag\n" if $DEBUG > 1;
343     my $agent = qsearchs('agent', { 'agentnum' => $agentnum } )
344       or return { 'error' => "Self-service agent #$agentnum does not exist" };
345     warn "$me has agent $agent\n" if $DEBUG > 1;
346     my @paybys = @{ $signup_info->{'payby'} };
347     $signup_info->{'hide_payment_fields'} = [];
348
349     my $gatewaynum = $conf->config('selfservice-payment_gateway');
350     my $force_gateway;
351     if ( $gatewaynum ) {
352       $force_gateway = qsearchs('payment_gateway', { gatewaynum => $gatewaynum });
353       warn "using forced gateway #$gatewaynum - " .
354         $force_gateway->gateway_username . '@' . $force_gateway->gateway_module
355         if $DEBUG > 1;
356       die "configured gatewaynum $gatewaynum not found!" if !$force_gateway;
357     }
358     foreach my $payby (@paybys) {
359       warn "$me checking $payby payment fields\n" if $DEBUG > 1;
360       my $hide = 0;
361       if ( FS::payby->realtime($payby) ) {
362         my $gateway = $force_gateway || 
363           $agent->payment_gateway( 'method'  => FS::payby->payby2bop($payby),
364                                    'nofatal' => 1,
365                                  );
366         if ( $gateway && $gateway->gateway_namespace
367                     eq 'Business::OnlineThirdPartyPayment'
368            ) {
369           warn "$me hiding $payby payment fields\n" if $DEBUG > 1;
370           $hide = 1;
371         }
372       }
373       push @{$signup_info->{'hide_payment_fields'}}, $hide;
374     } # foreach $payby
375     warn "$me done setting agent-specific payment flag\n" if $DEBUG > 1;
376
377     warn "$me setting agent-specific package list\n" if $DEBUG > 1;
378     $signup_info->{'part_pkg'} = $signup_info->{'agentnum2part_pkg'}{$agentnum}
379       unless @{ $signup_info->{'part_pkg'} };
380     warn "$me done setting agent-specific package list\n" if $DEBUG > 1;
381
382     warn "$me setting agent-specific adv. source list\n" if $DEBUG > 1;
383     $signup_info->{'part_referral'} =
384       [
385         map { $_->hashref }
386           qsearch( {
387                      'table'     => 'part_referral',
388                      'hashref'   => { 'disabled' => '' },
389                      'extra_sql' => "AND (    agentnum = $agentnum  ".
390                                     "      OR agentnum IS NULL    ) ",
391                    },
392                  )
393       ];
394     warn "$me done setting agent-specific adv. source list\n" if $DEBUG > 1;
395
396     $signup_info->{'agent_name'} = $agent->agent;
397
398     $signup_info->{'company_name'} = $conf->config('company_name', $agentnum);
399
400     #some of the above could probably be cached, too
401
402     my $signup_info_cache_agent = $cache->get("signup_info_cache_agent$agentnum");
403
404     if ( $signup_info_cache_agent ) {
405
406       warn "$me loading cached signup info for agentnum $agentnum\n"
407         if $DEBUG > 1;
408
409     } else {
410
411       warn "$me populating signup info cache for agentnum $agentnum\n"
412         if $DEBUG > 1;
413
414       $signup_info_cache_agent = {
415         #( map { $_ => scalar( $conf->config($_, $agentnum) ) }
416         #  qw( company_name ) ),
417         ( map { $_ => scalar( $conf->config("selfservice-$_", $agentnum ) ) }
418           qw( body_bgcolor box_bgcolor menu_bgcolor ) ),
419         ( map { $_ => join("\n", $conf->config("selfservice-$_", $agentnum ) ) }
420           qw( head body_header body_footer ) ),
421         ( map { $_ => join("\n", $conf->config("signup_server-$_", $agentnum ) ) }
422           qw( terms_of_service ) ),
423
424         ( map { $_ => scalar($conf->exists($_, $agentnum)) } 
425           qw(cust_main-require_phone agent-ship_address) ),
426       };
427
428       if ( $signup_info_cache_agent->{'agent-ship_address'} 
429            && $agent->agent_cust_main ) {
430
431         my $cust_main = $agent->agent_cust_main;
432         my $location = $cust_main->ship_location;
433         $signup_info_cache_agent->{"ship_$_"} = $location->get($_)
434           foreach qw( address1 city county state zip country );
435
436       }
437
438       $cache->set("signup_info_cache_agent$agentnum", $signup_info_cache_agent);
439
440     }
441
442     $signup_info->{$_} = $signup_info_cache_agent->{$_}
443       foreach keys %$signup_info_cache_agent;
444
445   }
446   # else {
447   # delete $signup_info->{'part_pkg'};
448   #}
449
450   warn "$me sorting package list\n" if $DEBUG > 1;
451   $signup_info->{'part_pkg'} = [ sort { $a->{pkg} cmp $b->{pkg} }  # case?
452                                       @{ $signup_info->{'part_pkg'} }
453                                ];
454   warn "$me done sorting package list\n" if $DEBUG > 1;
455
456   if ( exists $packet->{'session_id'} ) {
457     my $agent_signup_info = { %$signup_info };
458     delete $agent_signup_info->{agentnum2part_pkg};
459     $agent_signup_info->{'agent'} = $session->{'agent'};
460     return $agent_signup_info;
461   } 
462   elsif ( exists $packet->{'keys'} ) {
463     my @keys = @{ $packet->{'keys'} };
464     return { map { $_ => $signup_info->{$_} } @keys };
465   }
466   else {
467     return $signup_info;
468   }
469
470 }
471
472 sub domain_select_hash {
473   my $packet = shift;
474
475   my $response = {};
476
477   if ($packet->{pkgpart}) {
478     my $part_pkg = qsearchs('part_pkg' => { 'pkgpart' => $packet->{pkgpart} } );
479     #$packet->{svcpart} = $part_pkg->svcpart('svc_acct')
480     $packet->{svcpart} = $part_pkg->svcpart
481       if $part_pkg;
482   }
483
484   if ($packet->{svcpart}) {
485     my $part_svc = qsearchs('part_svc' => { 'svcpart' => $packet->{svcpart} } );
486     $response->{'domsvc'} = $part_svc->part_svc_column('domsvc')->columnvalue
487       if ($part_svc && $part_svc->part_svc_column('domsvc')->columnflag  eq 'D');
488   }
489
490   $response->{'domains'}
491     = { domain_select_hash FS::svc_acct( map { $_ => $packet->{$_} }
492                                                  qw(svcpart pkgnum)
493                                        ) };
494
495   $response;
496 }
497
498 sub new_customer {
499   my $packet = shift;
500
501   my $conf = new FS::Conf;
502   my $svc_x = $conf->config('signup_server-service') || 'svc_acct';
503
504   if ( $svc_x eq 'svc_acct' ) {
505   
506     #things that aren't necessary in base class, but are for signup server
507       #return "Passwords don't match"
508       #  if $hashref->{'_password'} ne $hashref->{'_password2'}
509     return { 'error' => gettext('empty_password') }
510       unless length($packet->{'_password'});
511     # a bit inefficient for large numbers of pops
512     return { 'error' => gettext('no_access_number_selected') }
513       unless $packet->{'popnum'} || !scalar(qsearch('svc_acct_pop',{} ));
514
515   }
516   elsif ( $svc_x eq 'svc_pbx' ) {
517     #possibly some validation will be needed
518   }
519
520   my $agentnum = get_agentnum($packet);
521   return $agentnum if ref($agentnum);
522
523   my ($bill_hash, $ship_hash);
524   foreach my $f (FS::cust_main->location_fields) {
525     # avoid having to change this in front-end code
526     $bill_hash->{$f} = $packet->{"bill_$f"} || $packet->{$f};
527     $ship_hash->{$f} = $packet->{"ship_$f"};
528   }
529
530   #shares some stuff with htdocs/edit/process/cust_main.cgi... take any
531   # common that are still here and library them.
532
533   my %cust_main = (
534     'agentnum' => $agentnum,
535     'refnum'   => $packet->{refnum}
536                   || $conf->config('signup_server-default_refnum'),
537     'tagnum'   => [ FS::part_tag->default_tags ],
538
539     ( map { $_ => $packet->{$_} } qw(
540             salesnum
541             ss stateid stateid_state
542
543             payby
544             payinfo paycvv paydate payname paystate paytype
545             paystart_month paystart_year payissue
546             payip
547
548             locale
549
550             referral_custnum comments
551           )
552     ),
553
554   );
555
556   my $template_custnum = $conf->config('signup_server-prepaid-template-custnum');
557   my $cust_main;
558   if ( $template_custnum && $packet->{prepaid_shortform} ) {
559
560     my $template_cust = qsearchs('cust_main', { 'custnum' => $template_custnum } );
561     return { 'error' => 'Configuration error' } unless $template_cust;
562     $cust_main = new FS::cust_main ( {
563       %cust_main,
564       map { $_ => $template_cust->$_ } qw( 
565         last first company daytime night fax mobile
566       ),
567     } );
568
569     $bill_hash = { $template_cust->bill_location->location_hash };
570     $ship_hash = { $template_cust->ship_location->location_hash };
571
572   } else {
573
574     $cust_main = new FS::cust_main ( {
575       %cust_main,
576       map { $_ => $packet->{$_} } qw(
577         last first company daytime night fax mobile
578         override_ban_warn
579       ),
580     } );
581   }
582
583   my $bill_location = FS::cust_location->new($bill_hash);
584   my $ship_location;
585   my $agent = qsearchs('agent', { 'agentnum' => $agentnum } );
586   if ( $conf->exists('agent-ship_address', $agentnum) 
587     && $agent->agent_custnum ) {
588
589     my $agent_cust_main = $agent->agent_cust_main;
590     my $prefix = length($agent_cust_main->ship_last) ? 'ship_' : '';
591     $ship_location = FS::cust_location->new({ 
592         $agent_cust_main->ship_location->location_hash
593     });
594
595   }
596   # we don't have an equivalent of the "same" checkbox in selfservice
597   # so is there a ship address, and if so, is it different from the billing 
598   # address?
599   elsif ( length($ship_hash->{address1}) > 0 and
600           grep { $bill_hash->{$_} ne $ship_hash->{$_} } keys(%$ship_hash)
601          ) {
602
603     $ship_location = FS::cust_location->new( $ship_hash );
604   
605   }
606   else {
607     $ship_location = $bill_location;
608   }
609
610   $cust_main->set('bill_location' => $bill_location);
611   $cust_main->set('ship_location' => $ship_location);
612
613   return { 'error' => "Illegal payment type" }
614     unless grep { $_ eq $packet->{'payby'} }
615                 $conf->config('signup_server-payby');
616
617   if (FS::payby->realtime($packet->{payby})
618     and not $conf->exists('signup_server-third_party_as_card')) {
619     my $payby = $packet->{payby};
620
621     my $agent = qsearchs('agent', { 'agentnum' => $agentnum });
622     return { 'error' => "Unknown reseller" }
623       unless $agent;
624
625     my $gw;
626     my $gatewaynum = $conf->config('selfservice-payment_gateway');
627     if ( $gatewaynum ) {
628       $gw = qsearchs('payment_gateway', { gatewaynum => $gatewaynum });
629       die "configured gatewaynum $gatewaynum not found!" if !$gw;
630     }
631     else {
632       $gw = $agent->payment_gateway( 'method'  => FS::payby->payby2bop($payby),
633                                      'nofatal' => 1,
634                                     );
635     }
636
637     $cust_main->payby('BILL')   # MCRD better?  no, that's for something else
638       if $gw && $gw->gateway_namespace eq 'Business::OnlineThirdPartyPayment';
639   }
640
641   return { 'error' => "CVV2 is required" }
642     if $cust_main->payby =~ /^(CARD|DCRD)$/
643     && ! $cust_main->paycvv
644     && $conf->exists('signup-require_cvv');
645
646   $cust_main->payinfo($cust_main->daytime)
647     if $cust_main->payby eq 'LECB' && ! $cust_main->payinfo;
648
649   if ( grep length($packet->{$_}), FS::cust_main->location_fields ) {
650     my $bill_hash;
651     foreach my $f (FS::cust_main->location_fields) {
652       $bill_hash->{$f} =  $packet->{$f};
653     }
654     my $bill_location = FS::cust_location->new($bill_hash);
655     $cust_main->set('bill_location' => $bill_location);
656     $cust_main->set('ship_location' => $bill_location);
657   }
658
659   my @invoicing_list = $packet->{'invoicing_list'}
660                          ? split( /\s*\,\s*/, $packet->{'invoicing_list'} )
661                          : ();
662
663   my %insert_options = ();
664
665   my @exempt_groups = grep /\S/, $conf->config('tax-cust_exempt-groups');
666   my @tax_exempt = grep { $packet->{"tax_$_"} eq 'Y' } @exempt_groups;
667   $insert_options{'tax_exemption'} = {
668     map { $_ => $packet->{"tax_$_".'_num'} } @tax_exempt
669   };
670
671   $packet->{'pkgpart'} =~ /^(\d+)$/ or '' =~ /^()$/;
672   my $pkgpart = $1;
673   return { 'error' => 'Please select a package' } unless $pkgpart; #msgcat
674
675   my $part_pkg =
676     qsearchs( 'part_pkg', { 'pkgpart' => $pkgpart } )
677       or return { 'error' => "WARNING: unknown pkgpart: $pkgpart" };
678
679   my $reg_code = '';
680   if ( $packet->{'reg_code'} ) {
681     $reg_code = qsearchs( 'reg_code', { 'code'     => $packet->{'reg_code'},
682                                         'agentnum' => $agentnum,             } )
683       or return { 'error' => 'Unknown registration code' };
684   }
685
686   my $cust_pkg = new FS::cust_pkg ( {
687     #later#'custnum' => $custnum,
688     'pkgpart'    => $packet->{'pkgpart'},
689     'promo_code' => $packet->{'promo_code'},
690     'reg_code'   => $packet->{'reg_code'},
691   } );
692   #my $error = $cust_pkg->check;
693   #return { 'error' => $error } if $error;
694
695   my @svc = ();
696   unless ( $svc_x eq 'none' ) {
697
698     my $svcpart = $part_pkg->svcpart($svc_x);
699     #should be all auto-magic and shit
700     if ( $svc_x eq 'svc_acct' ) {
701
702       my $svc = new FS::svc_acct {
703         'svcpart'   => $svcpart,
704         map { $_ => $packet->{$_} }
705           qw( username _password sec_phrase popnum domsvc ),
706       };
707       
708       my $error = $svc->is_password_allowed($packet->{_password});
709       $error = '' if $conf->config_bool('password-insecure', $agentnum);
710       return { error => $error } if $error;
711
712       my @acct_snarf;
713       my $snarfnum = 1;
714       while (    exists($packet->{"snarf_machine$snarfnum"})
715               && length($packet->{"snarf_machine$snarfnum"}) ) {
716         my $acct_snarf = new FS::acct_snarf ( {
717           'machine'   => $packet->{"snarf_machine$snarfnum"},
718           'protocol'  => $packet->{"snarf_protocol$snarfnum"},
719           'username'  => $packet->{"snarf_username$snarfnum"},
720           '_password' => $packet->{"snarf_password$snarfnum"},
721         } );
722         $snarfnum++;
723         push @acct_snarf, $acct_snarf;
724       }
725       $svc->child_objects( \@acct_snarf );
726       push @svc, $svc;
727
728     } elsif ( $svc_x eq 'svc_phone' ) {
729
730       push @svc, new FS::svc_phone ( {
731         'svcpart' => $svcpart,
732          map { $_ => $packet->{$_} }
733            qw( countrycode phonenum sip_password pin ),
734       } );
735
736     } elsif ( $svc_x eq 'svc_pbx' ) {
737
738       push @svc, new FS::svc_pbx ( {
739           'svcpart' => $svcpart,
740           map { $_ => $packet->{$_} } 
741             qw( id title ),
742           } );
743   
744     } else {
745       die "unknown signup service $svc_x";
746     }
747
748   }
749
750   if ($packet->{'mac_addr'} && $conf->exists('signup_server-mac_addr_svcparts'))
751   {
752
753     my %mac_addr_svcparts = map { $_ => 1 }
754                             $conf->config('signup_server-mac_addr_svcparts');
755     my @pkg_svc = grep { $_->quantity && $mac_addr_svcparts{$_->svcpart} }
756                   $cust_pkg->part_pkg->pkg_svc;
757
758     return { 'error' => 'No service defined to assign mac address' }
759       unless @pkg_svc;
760
761     my $svc = new FS::svc_acct {
762       'svcpart'   => $pkg_svc[0]->svcpart, #multiple matches? alas..
763       'username'  => $packet->{'mac_addr'},
764       '_password' => '', #blank as requested (set passwordmin to 0)
765     };
766
767     push @svc, $svc;
768
769   }
770
771   foreach my $svc ( @svc ) {
772     my $y = $svc->setdefault; # arguably should be in new method
773     return { 'error' => $y } if $y && !ref($y);
774     #$error = $svc->check;
775     #return { 'error' => $error } if $error;
776   }
777
778   #setup a job dependancy to delay provisioning
779   my $placeholder = new FS::queue ( {
780     'job'    => 'FS::ClientAPI::Signup::__placeholder',
781     'status' => 'locked',
782   } );
783   my $error = $placeholder->insert;
784   return { 'error' => $error } if $error;
785
786   use Tie::RefHash;
787   tie my %hash, 'Tie::RefHash';
788   %hash = ( $cust_pkg => \@svc );
789   #msgcat
790   $error = $cust_main->insert(
791     \%hash,
792     \@invoicing_list,
793     'depend_jobnum' => $placeholder->jobnum,
794      %insert_options,
795   );
796   if ( $error ) {
797     my $perror = $placeholder->delete;
798     $error .= " (Additionally, error removing placeholder: $perror)" if $perror;
799     return { 'error' => $error };
800   }
801
802   if ( $conf->exists('signup_server-realtime') ) {
803
804     #warn "$me Billing customer...\n" if $Debug;
805
806     my @cust_bill;
807     my $bill_error = $cust_main->bill(
808       'depend_jobnum' => $placeholder->jobnum,
809       'return_bill'   => \@cust_bill,
810     );
811     #warn "$me error billing new customer: $bill_error"
812     #  if $bill_error;
813
814     $bill_error = $cust_main->apply_payments_and_credits;
815     #warn "$me error applying payments and credits for".
816     #     " new customer: $bill_error"
817     #  if $bill_error;
818
819     unless ( $packet->{payby} eq 'PREPAY' ) {
820       $bill_error = $cust_main->realtime_collect(
821          method        => FS::payby->payby2bop( $packet->{payby} ),
822          depend_jobnum => $placeholder->jobnum,
823          selfservice   => 1,
824       );
825       #warn "$me error collecting from new customer: $bill_error"
826       #  if $bill_error;
827     }
828
829     if ($bill_error && ref($bill_error) eq 'HASH') {
830       return { 'error' => '_collect',
831                ( map { $_ => $bill_error->{$_} }
832                  qw(popup_url reference collectitems)
833                ),
834                amount => $cust_main->balance,
835              };
836     }
837
838     $bill_error = $cust_main->apply_payments_and_credits;
839     #warn "$me error applying payments and credits for".
840     #     " new customer: $bill_error"
841     #  if $bill_error;
842
843     if ( $cust_main->balance > 0 ) {
844
845       #this used to apply a credit, but now we can void invoices...
846       foreach my $cust_bill (@cust_bill) {
847         my $voiderror = $cust_bill->void('automatic payment failed');
848         warn "Error voiding cust bill after decline: $voiderror" if $voiderror;
849       }
850
851       #should check list for errors...
852       #$cust_main->suspend;
853       local $FS::svc_Common::noexport_hack = 1;
854       $cust_main->cancel('quiet'=>1);
855
856       my $perror = $placeholder->depended_delete;
857       warn "error removing provisioning jobs after decline: $perror" if $perror;
858       unless ( $perror ) {
859         $perror = $placeholder->delete;
860         warn "error removing placeholder after decline: $perror" if $perror;
861       }
862
863       return { 'error' => '_decline' };
864     }
865
866   }
867
868   if ( $reg_code ) {
869     $error = $reg_code->delete;
870     return { 'error' => $error } if $error;
871   }
872
873   $error = $placeholder->delete;
874   return { 'error' => $error } if $error;
875
876   if ( $conf->exists('signup-duplicate_cc-warn_hours') ) {
877     my $hours = $conf->config('signup-duplicate_cc-warn_hours');
878     my $ban = new FS::banned_pay $cust_main->_new_banned_pay_hashref;
879     $ban->end_date( int( time + $hours*3600 ) );
880     $ban->bantype('warn');
881     $ban->reason('signup-duplicate_cc-warn_hours');
882     $error = $ban->insert;
883     warn "WARNING: error inserting temporary banned_pay for ".
884          " signup-duplicate_cc-warn_hours (proceeding anyway): $error"
885       if $error;
886   }
887
888   my %return = ( 'error'          => '',
889                  'signup_service' => $svc_x,
890                  'custnum'        => $cust_main->custnum,
891                );
892
893   if ( $svc[0] ) {
894
895     $return{'svcnum'} = $svc[0]->svcnum;
896
897     if ( $svc_x eq 'svc_acct' ) {
898       $return{$_} = $svc[0]->$_() for qw( username _password );
899     } elsif ( $svc_x eq 'svc_phone' ) {
900       $return{$_} = $svc[0]->$_() for qw(countrycode phonenum sip_password pin);
901     } elsif ( $svc_x eq 'svc_pbx' ) {
902       #$return{$_} = $svc[0]->$_() for qw( ) #nothing yet
903      } else {
904       return {'error' => "configuration error: unknown signup service $svc_x"};
905       #die "unknown signup service $svc_x";
906       # return an error that's visible to someone somewhere
907     }
908
909   }
910
911   return \%return;
912
913 }
914
915 #false laziness w/ above
916 # fresh restart to support "free account" portals with 3.x/4.x-style
917 #  addressless accounts
918 # and a contact (for self-service login)
919 sub new_customer_minimal {
920   my $packet = shift;
921
922   my $conf = new FS::Conf;
923   my $svc_x = $conf->config('signup_server-service') || 'svc_acct';
924
925   if ( $svc_x eq 'svc_acct' ) {
926   
927     #things that aren't necessary in base class, but are for signup server
928       #return "Passwords don't match"
929       #  if $hashref->{'_password'} ne $hashref->{'_password2'}
930     return { 'error' => gettext('empty_password') }
931       unless length($packet->{'_password'});
932     # a bit inefficient for large numbers of pops
933     return { 'error' => gettext('no_access_number_selected') }
934       unless $packet->{'popnum'} || !scalar(qsearch('svc_acct_pop',{} ));
935
936   }
937   elsif ( $svc_x eq 'svc_pbx' ) {
938     #possibly some validation will be needed
939   }
940
941   my $agentnum = get_agentnum($packet);
942   return $agentnum if ref($agentnum);
943
944   #shares some stuff with htdocs/edit/process/cust_main.cgi... take any
945   # common that are still here and library them.
946
947   my $cust_main = new FS::cust_main ( {
948       'agentnum' => $agentnum,
949       'refnum'   => $packet->{refnum}
950                     || $conf->config('signup_server-default_refnum'),
951       'tagnum'   => [ FS::part_tag->default_tags ],
952       'payby'    => 'BILL',
953
954       map { $_ => $packet->{$_} } qw(
955         salesnum
956         last first company daytime night fax mobile
957         ss stateid stateid_state
958
959         payby
960         payinfo paycvv paydate payname paystate paytype
961         paystart_month paystart_year payissue
962         payip
963
964         locale
965       ),
966
967   } );
968
969   if ( grep length($packet->{$_}), FS::cust_main->location_fields ) {
970     my $bill_hash;
971     foreach my $f (FS::cust_main->location_fields) {
972       $bill_hash->{$f} =  $packet->{$f};
973     }
974     my $bill_location = FS::cust_location->new($bill_hash);
975     $cust_main->set('bill_location' => $bill_location);
976     $cust_main->set('ship_location' => $bill_location);
977   }
978
979   my @invoicing_list = $packet->{'invoicing_list'}
980                          ? split( /\s*\,\s*/, $packet->{'invoicing_list'} )
981                          : ();
982
983   use Tie::RefHash;
984   tie my %hash, 'Tie::RefHash', ();
985   my @svc = ();
986
987   $packet->{'pkgpart'} =~ /^(\d+)$/ or '' =~ /^()$/;
988   my $pkgpart = $1;
989
990   if ( $pkgpart ) {
991
992     my $part_pkg =
993       qsearchs( 'part_pkg', { 'pkgpart' => $pkgpart } )
994         or return { 'error' => "WARNING: unknown pkgpart: $pkgpart" };
995
996     my $cust_pkg = new FS::cust_pkg ( {
997       #later#'custnum' => $custnum,
998       'pkgpart'    => $packet->{'pkgpart'},
999     } );
1000     #my $error = $cust_pkg->check;
1001     #return { 'error' => $error } if $error;
1002
1003     unless ( $svc_x eq 'none' ) {
1004
1005       my $svcpart = $part_pkg->svcpart($svc_x);
1006       #should be all auto-magic and shit
1007       if ( $svc_x eq 'svc_acct' ) {
1008
1009         my $svc = new FS::svc_acct {
1010           'svcpart'   => $svcpart,
1011           map { $_ => $packet->{$_} }
1012             qw( username _password sec_phrase popnum domsvc ),
1013         };
1014
1015         push @svc, $svc;
1016
1017       } elsif ( $svc_x eq 'svc_phone' ) {
1018
1019         push @svc, new FS::svc_phone ( {
1020           'svcpart' => $svcpart,
1021            map { $_ => $packet->{$_} }
1022              qw( countrycode phonenum sip_password pin ),
1023         } );
1024
1025       } elsif ( $svc_x eq 'svc_pbx' ) {
1026
1027         push @svc, new FS::svc_pbx ( {
1028             'svcpart' => $svcpart,
1029             map { $_ => $packet->{$_} } 
1030               qw( id title ),
1031             } );
1032     
1033       } else {
1034         die "unknown signup service $svc_x";
1035       }
1036
1037     }
1038
1039     foreach my $svc ( @svc ) {
1040       my $y = $svc->setdefault; # arguably should be in new method
1041       return { 'error' => $y } if $y && !ref($y);
1042       #$error = $svc->check;
1043       #return { 'error' => $error } if $error;
1044     }
1045
1046     use Tie::RefHash;
1047     tie my %hash, 'Tie::RefHash';
1048     $hash{ $cust_pkg } = \@svc;
1049
1050   }
1051
1052   my %opt = ();
1053   if ( $invoicing_list[0] && $packet->{'_password'} ) {
1054     $opt{'contact'} = [
1055       new FS::contact { 'first'        => $cust_main->first,
1056                         'last'         => $cust_main->get('last'),
1057                         '_password'    => $packet->{'_password'},
1058                         'emailaddress' => $invoicing_list[0],
1059                         'selfservice_access' => 'Y',
1060                       }
1061     ];
1062   }
1063
1064   my $error = $cust_main->insert(
1065     \%hash,
1066     \@invoicing_list,
1067     %opt,
1068   );
1069   return { 'error' => $error } if $error;
1070
1071   my $session = { 'custnum' => $cust_main->custnum };
1072
1073   my $session_id;
1074   do {
1075     $session_id = sha512_hex(time(). {}. rand(). $$)
1076   } until ( ! defined _myaccount_cache->get($session_id) ); #just in case
1077
1078   _myaccount_cache->set( $session_id, $session, '1 hour' ); # 1 hour?
1079
1080   my %return = ( 'error'          => '',
1081                  'signup_service' => $svc_x,
1082                  'custnum'        => $cust_main->custnum,
1083                  'session_id'     => $session_id,
1084                  map { $_ => $cust_main->$_ } qw( first last company ),
1085                );
1086
1087   if ( $svc[0] ) {
1088
1089     $return{'svcnum'} = $svc[0]->svcnum;
1090
1091     if ( $svc_x eq 'svc_acct' ) {
1092       $return{$_} = $svc[0]->$_() for qw( username _password );
1093     } elsif ( $svc_x eq 'svc_phone' ) {
1094       $return{$_} = $svc[0]->$_() for qw(countrycode phonenum sip_password pin);
1095     } elsif ( $svc_x eq 'svc_pbx' ) {
1096       #$return{$_} = $svc[0]->$_() for qw( ) #nothing yet
1097      } else {
1098       return {'error' => "configuration error: unknown signup service $svc_x"};
1099       #die "unknown signup service $svc_x";
1100       # return an error that's visible to someone somewhere
1101     }
1102
1103   }
1104
1105   return \%return;
1106
1107 }
1108
1109 use vars qw( $myaccount_cache );
1110 sub _myaccount_cache {
1111   $myaccount_cache ||= new FS::ClientAPI_SessionCache( {
1112                          'namespace' => 'FS::ClientAPI::MyAccount',
1113                        } );
1114 }
1115
1116 sub capture_payment {
1117   my $packet = shift;
1118
1119   warn "$me capture_payment called on $packet\n" if $DEBUG;
1120
1121   ###
1122   # identify processor/gateway from called back URL
1123   ###
1124
1125   my $conf = new FS::Conf;
1126
1127   my $payment_gateway;
1128   if ( my $gwnum = $conf->config('selfservice-payment_gateway') ) {
1129     $payment_gateway = qsearchs('payment_gateway', { 'gatewaynum' => $gwnum })
1130       or die "configured gatewaynum $gwnum not found!";
1131   }
1132   else {
1133     my $url = $packet->{url};
1134
1135     $payment_gateway = qsearchs('payment_gateway', 
1136         { 'gateway_callback_url' => popurl(0, $url) } 
1137       );
1138     if (!$payment_gateway) { 
1139
1140       my ( $processor, $login, $password, $action, @bop_options ) =
1141         $conf->config('business-onlinepayment');
1142       $action ||= 'normal authorization';
1143       pop @bop_options if scalar(@bop_options) % 2 && $bop_options[-1] =~ /^\s*$/;
1144       die "No real-time processor is enabled - ".
1145           "did you set the business-onlinepayment configuration value?\n"
1146         unless $processor;
1147
1148       $payment_gateway = new FS::payment_gateway( {
1149         gateway_namespace => $conf->config('business-onlinepayment-namespace'),
1150         gateway_module    => $processor,
1151         gateway_username  => $login,
1152         gateway_password  => $password,
1153         gateway_action    => $action,
1154         options   => [ ( @bop_options ) ],
1155       });
1156     }
1157   }
1158  
1159   die "No real-time third party processor is enabled - ".
1160       "did you set the business-onlinepayment configuration value?\n*"
1161     unless $payment_gateway->gateway_namespace eq 'Business::OnlineThirdPartyPayment';
1162
1163   ###
1164   # locate pending transaction
1165   ###
1166
1167   eval "use Business::OnlineThirdPartyPayment";
1168   die $@ if $@;
1169
1170   my $transaction =
1171     new Business::OnlineThirdPartyPayment( $payment_gateway->gateway_module,
1172                                            @{ [ $payment_gateway->options ] },
1173                                          );
1174
1175   my $paypendingnum = $transaction->reference($packet->{data});
1176
1177   my $cust_pay_pending =
1178     qsearchs('cust_pay_pending', { paypendingnum => $paypendingnum } );
1179
1180   unless ($cust_pay_pending) {
1181     my $bill_error = "No payment is being processed with id $paypendingnum".
1182                      "; Transaction aborted.";
1183     return { error => '_decline', bill_error => $bill_error };
1184   }
1185
1186   if ($cust_pay_pending->status ne 'thirdparty') {
1187     my $bill_error = "Payment with id $paypendingnum is not thirdparty, but ".
1188                      $cust_pay_pending->status.  "; Transaction aborted.";
1189     return { error => '_decline', bill_error => $bill_error };
1190   }
1191
1192   my $cust_main = $cust_pay_pending->cust_main;
1193   if ( $packet->{cancel} ) {
1194     # the user has chosen not to make this payment
1195     # (probably should be a separate API call, but I don't want to duplicate
1196     # all of the above...which should eventually go away)
1197     my $error = $cust_pay_pending->delete;
1198     # don't show any errors related to this; they're not meaningful
1199     warn "error canceling pending payment $paypendingnum: $error\n" if $error;
1200     return { 'error'      => '_cancel',
1201              'session_id' => $cust_pay_pending->session_id };
1202   } else {
1203     # create the payment
1204     my $bill_error =
1205       $cust_main->realtime_botpp_capture( $cust_pay_pending, 
1206         %{$packet->{data}},
1207         apply => 1,
1208     );
1209
1210     return { 'error'      => ( $bill_error->{bill_error} ? '_decline' : '' ),
1211              %$bill_error,
1212            };
1213   }
1214
1215 }
1216
1217 =item get_agentnum PACKET
1218
1219 Given a PACKET from the signup server, looks up the agentnum to use for signing
1220 up a customer. This will use 'session_id' if the agent is authenticated,
1221 otherwise 'agentnum', otherwise the 'signup_server-default_agentnum' config. If
1222 the agent can't be found, returns an error packet.
1223
1224 =cut
1225
1226 sub get_agentnum {
1227   my $packet = shift;
1228   my $conf = new FS::Conf;
1229   my $agentnum;
1230   if ( exists $packet->{'session_id'} ) {
1231     my $cache = new FS::ClientAPI_SessionCache( {
1232       'namespace' => 'FS::ClientAPI::Agent',
1233     } );
1234     my $session = $cache->get($packet->{'session_id'});
1235     if ( $session ) {
1236       $agentnum = $session->{'agentnum'};
1237     } else {
1238       return { 'error' => "Can't resume session" }; #better error message
1239     }
1240   } else {
1241     $agentnum = $packet->{agentnum}
1242                 || $conf->config('signup_server-default_agentnum');
1243   }
1244   if ( $agentnum and FS::agent->count('agentnum = ?', $agentnum) ) {
1245     return $agentnum;
1246   }
1247   return { 'error' => 'Signup is not configured' };
1248 }
1249
1250 =item new_prospect PACKET
1251
1252 Creates a new L<FS::prospect_main> entry. PACKET must contain:
1253
1254 - either agentnum or session_id (unless signup_server-default_agentnum exists)
1255
1256 - refnum (unless signup_server-default_refnum exists)
1257
1258 - last and first (names), and optionally company and title
1259
1260 - address1, city, state, country, zip, and optionally address2
1261
1262 - emailaddress
1263
1264 - one or more of phone_daytime, phone_night, phone_mobile, and phone_fax
1265
1266 =cut
1267
1268 sub new_prospect {
1269
1270   my $packet = shift;
1271   warn "$me new_prospect called\n".Dumper($packet) if $DEBUG;
1272
1273   my $oldAutoCommit = $FS::UID::AutoCommit;
1274   local $FS::UID::AutoCommit = 0;
1275   my $dbh = dbh;
1276   my $conf = FS::Conf->new;
1277
1278   my $agentnum = get_agentnum($packet);
1279   return $agentnum if ref $agentnum;
1280   my $refnum = $packet->{refnum}
1281                || $conf->config('signup_server-default_refnum');
1282
1283   my $prospect = FS::prospect_main->new({
1284       'agentnum' => $agentnum,
1285       'refnum'   => $refnum,
1286       'company'  => $packet->{company},
1287   });
1288
1289   my $location = FS::cust_location->new;
1290   foreach ( qw(address1 address2 city county state zip country ) ) {
1291     $location->set($_, $packet->{$_});
1292   }
1293   $prospect->set('cust_location', $location);
1294   
1295   my $error = $prospect->insert; # also does location
1296   return { error => $error } if $error;
1297
1298   my $contact = FS::contact->new({
1299       prospectnum   => $prospect->prospectnum,
1300       locationnum   => $location->locationnum,
1301       invoice_dest  => 'Y',
1302   });
1303   # use emailaddress pseudo-field behavior here
1304   foreach (qw(last first title emailaddress)) {
1305     $contact->set($_, $packet->{$_});
1306   }
1307   $error = $contact->insert;
1308   if ( $error ) {
1309     $dbh->rollback if $oldAutoCommit;
1310     return { error => $error };
1311   }
1312
1313   foreach my $phone_type (qsearch('phone_type', {})) {
1314     my $key = 'phone_' . lc($phone_type->typename);
1315     my $phonenum = $packet->{$key};
1316     if ( $phonenum ) {
1317       # just to not have to supply country code from the other end
1318       my $number = Number::Phone->new($location->country, $phonenum);
1319       if (!$number) {
1320         $error = 'invalid phone number';
1321       } else {
1322         my $phone = FS::contact_phone->new({
1323             contactnum    => $contact->contactnum,
1324             phonenum      => $phonenum,
1325             countrycode   => $number->country_code,
1326             phonetypenum  => $phone_type->phonetypenum,
1327         });
1328         $error = $phone->insert;
1329       }
1330       if ( $error ) {
1331         $dbh->rollback if $oldAutoCommit;
1332         return { error => $phone_type->typename . ' phone: ' . $error };
1333       }
1334     }
1335   } # foreach $phone_type
1336   
1337   $dbh->commit if $oldAutoCommit;
1338   return { prospectnum => $prospect->prospectnum };
1339 }
1340
1341 1;