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