tax-exempt numbers during signup, RT#32299
[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 Digest::SHA qw(sha512_hex);
8 use FS::Conf;
9 use FS::Record qw(qsearch qsearchs dbdef);
10 use FS::CGI qw(popurl);
11 use FS::Msgcat qw(gettext);
12 use FS::Misc qw(card_types);
13 use FS::ClientAPI_SessionCache;
14 use FS::agent;
15 use FS::cust_main_county;
16 use FS::part_pkg;
17 use FS::svc_acct_pop;
18 use FS::cust_main;
19 use FS::cust_pkg;
20 use FS::svc_acct;
21 use FS::svc_phone;
22 use FS::acct_snarf;
23 use FS::queue;
24 use FS::reg_code;
25 use FS::payby;
26 use FS::banned_pay;
27
28 $DEBUG = 1;
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 warn Dumper($packet);
480
481   my $conf = new FS::Conf;
482   my $svc_x = $conf->config('signup_server-service') || 'svc_acct';
483
484   if ( $svc_x eq 'svc_acct' ) {
485   
486     #things that aren't necessary in base class, but are for signup server
487       #return "Passwords don't match"
488       #  if $hashref->{'_password'} ne $hashref->{'_password2'}
489     return { 'error' => gettext('empty_password') }
490       unless length($packet->{'_password'});
491     # a bit inefficient for large numbers of pops
492     return { 'error' => gettext('no_access_number_selected') }
493       unless $packet->{'popnum'} || !scalar(qsearch('svc_acct_pop',{} ));
494
495   }
496   elsif ( $svc_x eq 'svc_pbx' ) {
497     #possibly some validation will be needed
498   }
499
500   my $agentnum;
501   if ( exists $packet->{'session_id'} ) {
502     my $cache = new FS::ClientAPI_SessionCache( {
503       'namespace' => 'FS::ClientAPI::Agent',
504     } );
505     my $session = $cache->get($packet->{'session_id'});
506     if ( $session ) {
507       $agentnum = $session->{'agentnum'};
508     } else {
509       return { 'error' => "Can't resume session" }; #better error message
510     }
511   } else {
512     $agentnum = $packet->{agentnum}
513                 || $conf->config('signup_server-default_agentnum');
514   }
515
516   my ($bill_hash, $ship_hash);
517   foreach my $f (FS::cust_main->location_fields) {
518     # avoid having to change this in front-end code
519     $bill_hash->{$f} = $packet->{"bill_$f"} || $packet->{$f};
520     $ship_hash->{$f} = $packet->{"ship_$f"};
521   }
522
523   #shares some stuff with htdocs/edit/process/cust_main.cgi... take any
524   # common that are still here and library them.
525   my $template_custnum = $conf->config('signup_server-prepaid-template-custnum');
526   my $cust_main;
527   if ( $template_custnum && $packet->{prepaid_shortform} ) {
528
529     my $template_cust = qsearchs('cust_main', { 'custnum' => $template_custnum } );
530     return { 'error' => 'Configuration error' } unless $template_cust;
531     $cust_main = new FS::cust_main ( {
532       'agentnum'      => $agentnum,
533       'refnum'        => $packet->{refnum}
534                          || $conf->config('signup_server-default_refnum'),
535
536       ( map { $_ => $template_cust->$_ } qw( 
537               last first company daytime night fax mobile
538             )
539       ),
540
541       ( map { $_ => $packet->{$_} } qw(
542               ss stateid stateid_state
543
544               payby
545               payinfo paycvv paydate payname paystate paytype
546               paystart_month paystart_year payissue
547               payip
548
549               referral_custnum comments
550             )
551       ),
552
553     } );
554
555     $bill_hash = { $template_cust->bill_location->location_hash };
556     $ship_hash = { $template_cust->ship_location->location_hash };
557
558   } else {
559
560     $cust_main = new FS::cust_main ( {
561       #'custnum'          => '',
562       'agentnum'      => $agentnum,
563       'refnum'        => $packet->{refnum}
564                          || $conf->config('signup_server-default_refnum'),
565
566       map { $_ => $packet->{$_} } qw(
567         last first ss company 
568         daytime night fax mobile
569         stateid stateid_state
570         payby
571         payinfo paycvv paydate payname paystate paytype
572         paystart_month paystart_year payissue
573         payip
574         override_ban_warn
575         referral_custnum comments
576       ),
577
578     } );
579   }
580
581   my $bill_location = FS::cust_location->new($bill_hash);
582   my $ship_location;
583   my $agent = qsearchs('agent', { 'agentnum' => $agentnum } );
584   if ( $conf->exists('agent-ship_address', $agentnum) 
585     && $agent->agent_custnum ) {
586
587     my $agent_cust_main = $agent->agent_cust_main;
588     my $prefix = length($agent_cust_main->ship_last) ? 'ship_' : '';
589     $ship_location = FS::cust_location->new({ 
590         $agent_cust_main->ship_location->location_hash
591     });
592
593   }
594   # we don't have an equivalent of the "same" checkbox in selfservice
595   # so is there a ship address, and if so, is it different from the billing 
596   # address?
597   elsif ( length($ship_hash->{address1}) > 0 and
598           grep { $bill_hash->{$_} ne $ship_hash->{$_} } keys(%$ship_hash)
599          ) {
600
601     $ship_location = FS::cust_location->new( $ship_hash );
602   
603   }
604   else {
605     $ship_location = $bill_location;
606   }
607
608   $cust_main->set('bill_location' => $bill_location);
609   $cust_main->set('ship_location' => $ship_location);
610
611   return { 'error' => "Illegal payment type" }
612     unless grep { $_ eq $packet->{'payby'} }
613                 $conf->config('signup_server-payby');
614
615   if (FS::payby->realtime($packet->{payby})
616     and not $conf->exists('signup_server-third_party_as_card')) {
617     my $payby = $packet->{payby};
618
619     my $agent = qsearchs('agent', { 'agentnum' => $agentnum });
620     return { 'error' => "Unknown reseller" }
621       unless $agent;
622
623     my $gw;
624     my $gatewaynum = $conf->config('selfservice-payment_gateway');
625     if ( $gatewaynum ) {
626       $gw = qsearchs('payment_gateway', { gatewaynum => $gatewaynum });
627       die "configured gatewaynum $gatewaynum not found!" if !$gw;
628     }
629     else {
630       $gw = $agent->payment_gateway( 'method'  => FS::payby->payby2bop($payby),
631                                      'nofatal' => 1,
632                                     );
633     }
634
635     $cust_main->payby('BILL')   # MCRD better?
636       if $gw && $gw->gateway_namespace eq 'Business::OnlineThirdPartyPayment';
637   }
638
639   return { 'error' => "CVV2 is required" }
640     if $cust_main->payby =~ /^(CARD|DCRD)$/
641     && ! $cust_main->paycvv
642     && $conf->exists('signup-require_cvv');
643
644   $cust_main->payinfo($cust_main->daytime)
645     if $cust_main->payby eq 'LECB' && ! $cust_main->payinfo;
646
647   my @invoicing_list = $packet->{'invoicing_list'}
648                          ? split( /\s*\,\s*/, $packet->{'invoicing_list'} )
649                          : ();
650
651   my %insert_options = ();
652
653   my @exempt_groups = grep /\S/, $conf->config('tax-cust_exempt-groups');
654   my @tax_exempt = grep { $packet->{"tax_$_"} eq 'Y' } @exempt_groups;
655   $insert_options{'tax_exemption'} = {
656     map { $_ => $packet->{"tax_$_".'_num'} } @tax_exempt
657   };
658
659   $packet->{'pkgpart'} =~ /^(\d+)$/ or '' =~ /^()$/;
660   my $pkgpart = $1;
661   return { 'error' => 'Please select a package' } unless $pkgpart; #msgcat
662
663   my $part_pkg =
664     qsearchs( 'part_pkg', { 'pkgpart' => $pkgpart } )
665       or return { 'error' => "WARNING: unknown pkgpart: $pkgpart" };
666   my $svcpart = $part_pkg->svcpart($svc_x);
667
668   my $reg_code = '';
669   if ( $packet->{'reg_code'} ) {
670     $reg_code = qsearchs( 'reg_code', { 'code'     => $packet->{'reg_code'},
671                                         'agentnum' => $agentnum,             } )
672       or return { 'error' => 'Unknown registration code' };
673   }
674
675   my $cust_pkg = new FS::cust_pkg ( {
676     #later#'custnum' => $custnum,
677     'pkgpart'    => $packet->{'pkgpart'},
678     'promo_code' => $packet->{'promo_code'},
679     'reg_code'   => $packet->{'reg_code'},
680   } );
681   #my $error = $cust_pkg->check;
682   #return { 'error' => $error } if $error;
683
684   #should be all auto-magic and shit
685   my @svc = ();
686   if ( $svc_x eq 'svc_acct' ) {
687
688     my $svc = new FS::svc_acct {
689       'svcpart'   => $svcpart,
690       map { $_ => $packet->{$_} }
691         qw( username _password sec_phrase popnum domsvc ),
692     };
693
694     my @acct_snarf;
695     my $snarfnum = 1;
696     while (    exists($packet->{"snarf_machine$snarfnum"})
697             && length($packet->{"snarf_machine$snarfnum"}) ) {
698       my $acct_snarf = new FS::acct_snarf ( {
699         'machine'   => $packet->{"snarf_machine$snarfnum"},
700         'protocol'  => $packet->{"snarf_protocol$snarfnum"},
701         'username'  => $packet->{"snarf_username$snarfnum"},
702         '_password' => $packet->{"snarf_password$snarfnum"},
703       } );
704       $snarfnum++;
705       push @acct_snarf, $acct_snarf;
706     }
707     $svc->child_objects( \@acct_snarf );
708     push @svc, $svc;
709
710   } elsif ( $svc_x eq 'svc_phone' ) {
711
712     push @svc, new FS::svc_phone ( {
713       'svcpart' => $svcpart,
714        map { $_ => $packet->{$_} }
715          qw( countrycode phonenum sip_password pin ),
716     } );
717
718   } elsif ( $svc_x eq 'svc_pbx' ) {
719
720     push @svc, new FS::svc_pbx ( {
721         'svcpart' => $svcpart,
722         map { $_ => $packet->{$_} } 
723           qw( id title ),
724         } );
725   
726   } else {
727     die "unknown signup service $svc_x";
728   }
729
730   if ($packet->{'mac_addr'} && $conf->exists('signup_server-mac_addr_svcparts'))
731   {
732
733     my %mac_addr_svcparts = map { $_ => 1 }
734                             $conf->config('signup_server-mac_addr_svcparts');
735     my @pkg_svc = grep { $_->quantity && $mac_addr_svcparts{$_->svcpart} }
736                   $cust_pkg->part_pkg->pkg_svc;
737
738     return { 'error' => 'No service defined to assign mac address' }
739       unless @pkg_svc;
740
741     my $svc = new FS::svc_acct {
742       'svcpart'   => $pkg_svc[0]->svcpart, #multiple matches? alas..
743       'username'  => $packet->{'mac_addr'},
744       '_password' => '', #blank as requested (set passwordmin to 0)
745     };
746
747     push @svc, $svc;
748
749   }
750
751   foreach my $svc ( @svc ) {
752     my $y = $svc->setdefault; # arguably should be in new method
753     return { 'error' => $y } if $y && !ref($y);
754     #$error = $svc->check;
755     #return { 'error' => $error } if $error;
756   }
757
758   #setup a job dependancy to delay provisioning
759   my $placeholder = new FS::queue ( {
760     'job'    => 'FS::ClientAPI::Signup::__placeholder',
761     'status' => 'locked',
762   } );
763   my $error = $placeholder->insert;
764   return { 'error' => $error } if $error;
765
766   use Tie::RefHash;
767   tie my %hash, 'Tie::RefHash';
768   %hash = ( $cust_pkg => \@svc );
769   #msgcat
770   $error = $cust_main->insert(
771     \%hash,
772     \@invoicing_list,
773     'depend_jobnum' => $placeholder->jobnum,
774      %insert_options,
775   );
776   if ( $error ) {
777     my $perror = $placeholder->delete;
778     $error .= " (Additionally, error removing placeholder: $perror)" if $perror;
779     return { 'error' => $error };
780   }
781
782   if ( $conf->exists('signup_server-realtime') ) {
783
784     #warn "$me Billing customer...\n" if $Debug;
785
786     my $bill_error = $cust_main->bill( 'depend_jobnum'=>$placeholder->jobnum );
787     #warn "$me error billing new customer: $bill_error"
788     #  if $bill_error;
789
790     $bill_error = $cust_main->apply_payments_and_credits;
791     #warn "$me error applying payments and credits for".
792     #     " new customer: $bill_error"
793     #  if $bill_error;
794
795     unless ( $packet->{payby} eq 'PREPAY' ) {
796       $bill_error = $cust_main->realtime_collect(
797          method        => FS::payby->payby2bop( $packet->{payby} ),
798          depend_jobnum => $placeholder->jobnum,
799          selfservice   => 1,
800       );
801       #warn "$me error collecting from new customer: $bill_error"
802       #  if $bill_error;
803     }
804
805     if ($bill_error && ref($bill_error) eq 'HASH') {
806       return { 'error' => '_collect',
807                ( map { $_ => $bill_error->{$_} }
808                  qw(popup_url reference collectitems)
809                ),
810                amount => $cust_main->balance,
811              };
812     }
813
814     $bill_error = $cust_main->apply_payments_and_credits;
815     #warn "$me error applying payments and credits for".
816     #     " new customer: $bill_error"
817     #  if $bill_error;
818
819     if ( $cust_main->balance > 0 ) {
820
821       #this makes sense.  credit is "un-doing" the invoice
822       $cust_main->credit( $cust_main->balance, 'signup server decline',
823                           'reason_type' => $conf->config('signup_credit_type'),
824                         );
825       $cust_main->apply_credits;
826
827       #should check list for errors...
828       #$cust_main->suspend;
829       local $FS::svc_Common::noexport_hack = 1;
830       $cust_main->cancel('quiet'=>1);
831
832       my $perror = $placeholder->depended_delete;
833       warn "error removing provisioning jobs after decline: $perror" if $perror;
834       unless ( $perror ) {
835         $perror = $placeholder->delete;
836         warn "error removing placeholder after decline: $perror" if $perror;
837       }
838
839       return { 'error' => '_decline' };
840     }
841
842   }
843
844   if ( $reg_code ) {
845     $error = $reg_code->delete;
846     return { 'error' => $error } if $error;
847   }
848
849   $error = $placeholder->delete;
850   return { 'error' => $error } if $error;
851
852   if ( $conf->exists('signup-duplicate_cc-warn_hours') ) {
853     my $hours = $conf->config('signup-duplicate_cc-warn_hours');
854     my $ban = new FS::banned_pay $cust_main->_new_banned_pay_hashref;
855     $ban->end_date( int( time + $hours*3600 ) );
856     $ban->bantype('warn');
857     $ban->reason('signup-duplicate_cc-warn_hours');
858     $error = $ban->insert;
859     warn "WARNING: error inserting temporary banned_pay for ".
860          " signup-duplicate_cc-warn_hours (proceeding anyway): $error"
861       if $error;
862   }
863
864   my %return = ( 'error'          => '',
865                  'signup_service' => $svc_x,
866                  'custnum'        => $cust_main->custnum,
867                );
868
869   if ( $svc[0] ) {
870
871     $return{'svcnum'} = $svc[0]->svcnum;
872
873     if ( $svc_x eq 'svc_acct' ) {
874       $return{$_} = $svc[0]->$_() for qw( username _password );
875     } elsif ( $svc_x eq 'svc_phone' ) {
876       $return{$_} = $svc[0]->$_() for qw(countrycode phonenum sip_password pin);
877     } elsif ( $svc_x eq 'svc_pbx' ) {
878       #$return{$_} = $svc[0]->$_() for qw( ) #nothing yet
879      } else {
880       return {'error' => "configuration error: unknown signup service $svc_x"};
881       #die "unknown signup service $svc_x";
882       # return an error that's visible to someone somewhere
883     }
884
885   }
886
887   return \%return;
888
889 }
890
891 #false laziness w/ above
892 # fresh restart to support "free account" portals with 3.x/4.x-style
893 #  addressless accounts
894 # and a contact (for self-service login)
895 sub new_customer_minimal {
896   my $packet = shift;
897
898   my $conf = new FS::Conf;
899   my $svc_x = $conf->config('signup_server-service') || 'svc_acct';
900
901   if ( $svc_x eq 'svc_acct' ) {
902   
903     #things that aren't necessary in base class, but are for signup server
904       #return "Passwords don't match"
905       #  if $hashref->{'_password'} ne $hashref->{'_password2'}
906     return { 'error' => gettext('empty_password') }
907       unless length($packet->{'_password'});
908     # a bit inefficient for large numbers of pops
909     return { 'error' => gettext('no_access_number_selected') }
910       unless $packet->{'popnum'} || !scalar(qsearch('svc_acct_pop',{} ));
911
912   }
913   elsif ( $svc_x eq 'svc_pbx' ) {
914     #possibly some validation will be needed
915   }
916
917   my $agentnum;
918   if ( exists $packet->{'session_id'} ) {
919     my $cache = new FS::ClientAPI_SessionCache( {
920       'namespace' => 'FS::ClientAPI::Agent',
921     } );
922     my $session = $cache->get($packet->{'session_id'});
923     if ( $session ) {
924       $agentnum = $session->{'agentnum'};
925     } else {
926       return { 'error' => "Can't resume session" }; #better error message
927     }
928   } else {
929     $agentnum = $packet->{agentnum}
930                 || $conf->config('signup_server-default_agentnum');
931   }
932
933   #shares some stuff with htdocs/edit/process/cust_main.cgi... take any
934   # common that are still here and library them.
935
936   my $cust_main = new FS::cust_main ( {
937       #'custnum'          => '',
938       'agentnum'      => $agentnum,
939       'refnum'        => $packet->{refnum}
940                          || $conf->config('signup_server-default_refnum'),
941       'payby'         => 'BILL',
942
943       map { $_ => $packet->{$_} } qw(
944         last first ss company 
945         daytime night fax mobile
946       ),
947
948   } );
949
950   my @invoicing_list = $packet->{'invoicing_list'}
951                          ? split( /\s*\,\s*/, $packet->{'invoicing_list'} )
952                          : ();
953
954   use Tie::RefHash;
955   tie my %hash, 'Tie::RefHash', ();
956   my @svc = ();
957
958   $packet->{'pkgpart'} =~ /^(\d+)$/ or '' =~ /^()$/;
959   my $pkgpart = $1;
960
961   if ( $pkgpart ) {
962
963     my $part_pkg =
964       qsearchs( 'part_pkg', { 'pkgpart' => $pkgpart } )
965         or return { 'error' => "WARNING: unknown pkgpart: $pkgpart" };
966     my $svcpart = $part_pkg->svcpart($svc_x);
967
968     my $cust_pkg = new FS::cust_pkg ( {
969       #later#'custnum' => $custnum,
970       'pkgpart'    => $packet->{'pkgpart'},
971     } );
972     #my $error = $cust_pkg->check;
973     #return { 'error' => $error } if $error;
974
975     #should be all auto-magic and shit
976     if ( $svc_x eq 'svc_acct' ) {
977
978       my $svc = new FS::svc_acct {
979         'svcpart'   => $svcpart,
980         map { $_ => $packet->{$_} }
981           qw( username _password sec_phrase popnum domsvc ),
982       };
983
984       push @svc, $svc;
985
986     } elsif ( $svc_x eq 'svc_phone' ) {
987
988       push @svc, new FS::svc_phone ( {
989         'svcpart' => $svcpart,
990          map { $_ => $packet->{$_} }
991            qw( countrycode phonenum sip_password pin ),
992       } );
993
994     } elsif ( $svc_x eq 'svc_pbx' ) {
995
996       push @svc, new FS::svc_pbx ( {
997           'svcpart' => $svcpart,
998           map { $_ => $packet->{$_} } 
999             qw( id title ),
1000           } );
1001     
1002     } else {
1003       die "unknown signup service $svc_x";
1004     }
1005
1006     foreach my $svc ( @svc ) {
1007       my $y = $svc->setdefault; # arguably should be in new method
1008       return { 'error' => $y } if $y && !ref($y);
1009       #$error = $svc->check;
1010       #return { 'error' => $error } if $error;
1011     }
1012
1013     use Tie::RefHash;
1014     tie my %hash, 'Tie::RefHash';
1015     $hash{ $cust_pkg } = \@svc;
1016
1017   }
1018
1019   my %opt = ();
1020   if ( $invoicing_list[0] && $packet->{'_password'} ) {
1021     $opt{'contact'} = [
1022       new FS::contact { 'first'        => $cust_main->first,
1023                         'last'         => $cust_main->get('last'),
1024                         '_password'    => $packet->{'_password'},
1025                         'emailaddress' => $invoicing_list[0],
1026                         'selfservice_access' => 'Y',
1027                       }
1028     ];
1029   }
1030
1031   my $error = $cust_main->insert(
1032     \%hash,
1033     \@invoicing_list,
1034     %opt,
1035   );
1036   return { 'error' => $error } if $error;
1037
1038   my $session = { 'custnum' => $cust_main->custnum };
1039
1040   my $session_id;
1041   do {
1042     $session_id = sha1_hex(time(). {}. rand(). $$)
1043   } until ( ! defined _myaccount_cache->get($session_id) ); #just in case
1044
1045   _cache->set( $session_id, $session, '1 hour' ); # 1 hour?
1046
1047   my %return = ( 'error'          => '',
1048                  'signup_service' => $svc_x,
1049                  'custnum'        => $cust_main->custnum,
1050                  'session_id'     => $session_id,
1051                );
1052
1053   if ( $svc[0] ) {
1054
1055     $return{'svcnum'} = $svc[0]->svcnum;
1056
1057     if ( $svc_x eq 'svc_acct' ) {
1058       $return{$_} = $svc[0]->$_() for qw( username _password );
1059     } elsif ( $svc_x eq 'svc_phone' ) {
1060       $return{$_} = $svc[0]->$_() for qw(countrycode phonenum sip_password pin);
1061     } elsif ( $svc_x eq 'svc_pbx' ) {
1062       #$return{$_} = $svc[0]->$_() for qw( ) #nothing yet
1063      } else {
1064       return {'error' => "configuration error: unknown signup service $svc_x"};
1065       #die "unknown signup service $svc_x";
1066       # return an error that's visible to someone somewhere
1067     }
1068
1069   }
1070
1071   return \%return;
1072
1073 }
1074
1075 use vars qw( $myaccount_cache );
1076 sub _myaccount_cache {
1077   $myaccount_cache ||= new FS::ClientAPI_SessionCache( {
1078                          'namespace' => 'FS::ClientAPI::MyAccount',
1079                        } );
1080 }
1081
1082 sub capture_payment {
1083   my $packet = shift;
1084
1085   warn "$me capture_payment called on $packet\n" if $DEBUG;
1086
1087   ###
1088   # identify processor/gateway from called back URL
1089   ###
1090
1091   my $conf = new FS::Conf;
1092
1093   my $payment_gateway;
1094   if ( my $gwnum = $conf->config('selfservice-payment_gateway') ) {
1095     $payment_gateway = qsearchs('payment_gateway', { 'gatewaynum' => $gwnum })
1096       or die "configured gatewaynum $gwnum not found!";
1097   }
1098   else {
1099     my $url = $packet->{url};
1100
1101     $payment_gateway = qsearchs('payment_gateway', 
1102         { 'gateway_callback_url' => popurl(0, $url) } 
1103       );
1104     if (!$payment_gateway) { 
1105
1106       my ( $processor, $login, $password, $action, @bop_options ) =
1107         $conf->config('business-onlinepayment');
1108       $action ||= 'normal authorization';
1109       pop @bop_options if scalar(@bop_options) % 2 && $bop_options[-1] =~ /^\s*$/;
1110       die "No real-time processor is enabled - ".
1111           "did you set the business-onlinepayment configuration value?\n"
1112         unless $processor;
1113
1114       $payment_gateway = new FS::payment_gateway( {
1115         gateway_namespace => $conf->config('business-onlinepayment-namespace'),
1116         gateway_module    => $processor,
1117         gateway_username  => $login,
1118         gateway_password  => $password,
1119         gateway_action    => $action,
1120         options   => [ ( @bop_options ) ],
1121       });
1122     }
1123   }
1124  
1125   die "No real-time third party processor is enabled - ".
1126       "did you set the business-onlinepayment configuration value?\n*"
1127     unless $payment_gateway->gateway_namespace eq 'Business::OnlineThirdPartyPayment';
1128
1129   ###
1130   # locate pending transaction
1131   ###
1132
1133   eval "use Business::OnlineThirdPartyPayment";
1134   die $@ if $@;
1135
1136   my $transaction =
1137     new Business::OnlineThirdPartyPayment( $payment_gateway->gateway_module,
1138                                            @{ [ $payment_gateway->options ] },
1139                                          );
1140
1141   my $paypendingnum = $transaction->reference($packet->{data});
1142
1143   my $cust_pay_pending =
1144     qsearchs('cust_pay_pending', { paypendingnum => $paypendingnum } );
1145
1146   unless ($cust_pay_pending) {
1147     my $bill_error = "No payment is being processed with id $paypendingnum".
1148                      "; Transaction aborted.";
1149     return { error => '_decline', bill_error => $bill_error };
1150   }
1151
1152   if ($cust_pay_pending->status ne 'thirdparty') {
1153     my $bill_error = "Payment with id $paypendingnum is not thirdparty, but ".
1154                      $cust_pay_pending->status.  "; Transaction aborted.";
1155     return { error => '_decline', bill_error => $bill_error };
1156   }
1157
1158   my $cust_main = $cust_pay_pending->cust_main;
1159   if ( $packet->{cancel} ) {
1160     # the user has chosen not to make this payment
1161     # (probably should be a separate API call, but I don't want to duplicate
1162     # all of the above...which should eventually go away)
1163     my $error = $cust_pay_pending->delete;
1164     # don't show any errors related to this; they're not meaningful
1165     warn "error canceling pending payment $paypendingnum: $error\n" if $error;
1166     return { 'error'      => '_cancel',
1167              'session_id' => $cust_pay_pending->session_id };
1168   } else {
1169     # create the payment
1170     my $bill_error =
1171       $cust_main->realtime_botpp_capture( $cust_pay_pending, 
1172         %{$packet->{data}},
1173         apply => 1,
1174     );
1175
1176     return { 'error'      => ( $bill_error->{bill_error} ? '_decline' : '' ),
1177              %$bill_error,
1178            };
1179   }
1180
1181 }
1182
1183 1;