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