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