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 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
27 $DEBUG = 0;
28 $me = '[FS::ClientAPI::Signup]';
29
30 sub clear_cache {
31   warn "$me clear_cache called\n" if $DEBUG;
32   my $cache = new FS::ClientAPI_SessionCache( {
33       'namespace' => 'FS::ClientAPI::Signup',
34   } );
35   $cache->clear();
36   return {};
37 }
38
39 sub signup_info {
40   my $packet = shift;
41
42   warn "$me signup_info called on $packet\n" if $DEBUG;
43
44   my $conf = new FS::Conf;
45   my $svc_x = $conf->config('signup_server-service') || 'svc_acct';
46
47   my $cache = new FS::ClientAPI_SessionCache( {
48     'namespace' => 'FS::ClientAPI::Signup',
49   } );
50   my $signup_info_cache = $cache->get('signup_info_cache');
51
52   if ( $signup_info_cache ) {
53
54     warn "$me loading cached signup info\n" if $DEBUG > 1;
55
56   } else {
57
58     warn "$me populating signup info cache\n" if $DEBUG > 1;
59
60     my $agentnum2part_pkg = 
61       {
62         map {
63           my $agent = $_;
64           my $href = $agent->pkgpart_hashref;
65           $agent->agentnum =>
66             [
67               map { { 'payby'       => [ $_->payby ],
68                       'freq_pretty' => $_->freq_pretty,
69                       'options'     => { $_->options },
70                       %{$_->hashref}
71                   } }
72                 grep { $_->svcpart($svc_x)
73                        && ( $href->{ $_->pkgpart }
74                             || ( $_->agentnum
75                                  && $_->agentnum == $agent->agentnum
76                                )
77                           )
78                      }
79                   qsearch( 'part_pkg', { 'disabled' => '' } )
80             ];
81         } qsearch('agent', { 'disabled' => '' })
82       };
83
84     my $msgcat = { map { $_=>gettext($_) }
85                        qw( passwords_dont_match invalid_card unknown_card_type
86                            not_a empty_password illegal_or_empty_text )
87                  };
88     warn "msgcat: ". Dumper($msgcat). "\n" if $DEBUG > 2;
89
90     my $label = { map { $_ => FS::Msgcat::_gettext($_) }
91                       qw( stateid stateid_state )
92                 };
93     warn "label: ". Dumper($label). "\n" if $DEBUG > 2;
94
95     my @agent_fields = qw( agentnum agent );
96
97     my @bools = qw( emailinvoiceonly security_phrase );
98
99     my @signup_bools = qw( no_company recommend_daytime recommend_email );
100
101     my @signup_server_scalars = qw( default_pkgpart default_svcpart default_domsvc );
102
103     my @selfservice_textareas = qw( head body_header body_footer );
104
105     my @selfservice_scalars = qw(
106       body_bgcolor box_bgcolor
107       text_color link_color vlink_color hlink_color alink_color
108       font title_color title_align title_size menu_bgcolor menu_fontsize
109     );
110
111     #XXX my @selfservice_bools = qw(
112     #  menu_skipblanks menu_skipheadings menu_nounderline
113     #);
114
115     #my $selfservice_binaries = qw(
116     #  title_left_image title_right_image
117     #  menu_top_image menu_body_image menu_bottom_image
118     #);
119
120     $signup_info_cache = {
121
122       'cust_main_county' => [ map $_->hashref,
123                                   qsearch('cust_main_county', {} )
124                             ],
125
126       'agent' => [ map { my $agent = $_;
127                          +{ map { $_ => $agent->get($_) } @agent_fields }
128                        }
129                        qsearch('agent', { 'disabled' => '' } )
130                  ],
131
132       'part_referral' => [ map $_->hashref,
133                                qsearch('part_referral', { 'disabled' => '' } )
134                          ],
135
136       'agentnum2part_pkg' => $agentnum2part_pkg,
137
138       'svc_acct_pop' => [ map $_->hashref, qsearch('svc_acct_pop',{} ) ],
139
140       'emailinvoiceonly' => $conf->exists('emailinvoiceonly'),
141
142       'security_phrase' => $conf->exists('security_phrase'),
143
144       'nomadix' => $conf->exists('signup_server-nomadix'),
145
146       'payby' => [ $conf->config('signup_server-payby') ],
147
148       'payby_longname' => [ map { FS::payby->longname($_) } 
149                             $conf->config('signup_server-payby') ],
150
151       'card_types' => card_types(),
152
153       ( map { $_ => $conf->exists("signup-$_") } @signup_bools ),
154
155       ( map { $_ => scalar($conf->config("signup_server-$_")) }
156             @signup_server_scalars
157       ),
158
159       ( map { $_ => join("\n", $conf->config("selfservice-$_")) }
160             @selfservice_textareas
161       ),
162       ( map { $_ => scalar($conf->config("selfservice-$_")) }
163             @selfservice_scalars
164       ),
165
166       #( map { $_ => scalar($conf->config_binary("selfservice-$_")) }
167       #      @selfservice_binaries
168       #),
169
170       'agentnum2part_pkg'  => $agentnum2part_pkg,
171       'svc_acct_pop'       => [ map $_->hashref, qsearch('svc_acct_pop',{} ) ],
172       'nomadix'            => $conf->exists('signup_server-nomadix'),
173       'payby'              => [ $conf->config('signup_server-payby') ],
174       'card_types'         => card_types(),
175       'paytypes'           => [ @FS::cust_main::paytypes ],
176       'cvv_enabled'        => 1,
177       'require_cvv'        => $conf->exists('signup-require_cvv'),
178       'stateid_enabled'    => $conf->exists('show_stateid'),
179       'paystate_enabled'   => $conf->exists('show_bankstate'),
180       'exempt_groups'      => [ grep /\S/, $conf->config('tax-cust_exempt-groups') ],
181       'ship_enabled'       => 1,
182       'msgcat'             => $msgcat,
183       'label'              => $label,
184       'statedefault'       => scalar($conf->config('statedefault')) || 'CA',
185       'countrydefault'     => scalar($conf->config('countrydefault')) || 'US',
186       'refnum'             => scalar($conf->config('signup_server-default_refnum')),
187       'signup_service'     => $svc_x,
188       'company_name'       => scalar($conf->config('company_name')),
189       #per-agent?
190       'logo'               => scalar($conf->config_binary('logo.png')),
191       'prepaid_template_custnum' => $conf->exists('signup_server-prepaid-template-custnum'),
192     };
193
194     $cache->set('signup_info_cache', $signup_info_cache);
195
196   }
197
198   my $signup_info = { %$signup_info_cache };
199   warn "$me signup info loaded\n" if $DEBUG > 1;
200   warn Dumper($signup_info). "\n" if $DEBUG > 2;
201
202   my @addl = qw( signup_server-classnum2 signup_server-classnum3 );
203
204   if ( grep { $conf->exists($_) } @addl ) {
205   
206     $signup_info->{optional_packages} = [];
207
208     foreach my $addl ( @addl ) {
209
210       warn "$me adding optional package info\n" if $DEBUG > 1;
211
212       my $classnum = $conf->config($addl) or next;
213
214       my @pkgs = map { {
215                          'freq_pretty' => $_->freq_pretty,
216                          'options'     => { $_->options },
217                          %{ $_->hashref }
218                        };
219                      }
220                      qsearch( 'part_pkg', { classnum => $classnum } );
221
222       push @{$signup_info->{optional_packages}}, \@pkgs;
223
224       warn "$me done adding opt. package info for $classnum\n" if $DEBUG > 1;
225
226     }
227
228   }
229
230   my $agentnum = $packet->{'agentnum'}
231                  || $conf->config('signup_server-default_agentnum');
232   $agentnum =~ /^(\d*)$/ or die "illegal agentnum";
233   $agentnum = $1;
234
235   my $session = '';
236   if ( exists $packet->{'session_id'} ) {
237
238     warn "$me loading agent session\n" if $DEBUG > 1;
239     my $cache = new FS::ClientAPI_SessionCache( {
240       'namespace' => 'FS::ClientAPI::Agent',
241     } );
242     $session = $cache->get($packet->{'session_id'});
243     if ( $session ) {
244       $agentnum = $session->{'agentnum'};
245     } else {
246       return { 'error' => "Can't resume session" }; #better error message
247     }
248     warn "$me done loading agent session\n" if $DEBUG > 1;
249
250   } elsif ( exists $packet->{'customer_session_id'} ) {
251
252     warn "$me loading customer session\n" if $DEBUG > 1;
253     my $cache = new FS::ClientAPI_SessionCache( {
254       'namespace' => 'FS::ClientAPI::MyAccount',
255     } );
256     $session = $cache->get($packet->{'customer_session_id'});
257     if ( $session ) {
258       my $custnum = $session->{'custnum'};
259       my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum });
260       return { 'error' => "Can't find your customer record" } unless $cust_main;
261       $agentnum = $cust_main->agentnum;
262     } else {
263       return { 'error' => "Can't resume session" }; #better error message
264     }
265     warn "$me done loading customer session\n" if $DEBUG > 1;
266
267   }
268
269   $signup_info->{'part_pkg'} = [];
270
271   if ( $packet->{'reg_code'} ) {
272
273     warn "$me setting package list via reg_code\n" if $DEBUG > 1;
274
275     $signup_info->{'part_pkg'} = 
276       [ map { { 'payby'       => [ $_->payby ],
277                 'freq_pretty' => $_->freq_pretty,
278                 'options'     => { $_->options },
279                 %{$_->hashref}
280               };
281             }
282           grep { $_->svcpart($svc_x) }
283           map { $_->part_pkg }
284             qsearchs( 'reg_code', { 'code'     => $packet->{'reg_code'},
285                                     'agentnum' => $agentnum,              } )
286
287       ];
288
289     $signup_info->{'error'} = 'Unknown registration code'
290       unless @{ $signup_info->{'part_pkg'} };
291
292     warn "$me done setting package list via reg_code\n" if $DEBUG > 1;
293
294   } elsif ( $packet->{'promo_code'} ) {
295
296     warn "$me setting package list via promo_code\n" if $DEBUG > 1;
297
298     $signup_info->{'part_pkg'} =
299       [ map { { 'payby'   => [ $_->payby ],
300                 'freq_pretty' => $_->freq_pretty,
301                 'options'     => { $_->options },
302                 %{$_->hashref}
303             } }
304           grep { $_->svcpart($svc_x) }
305             qsearch( 'part_pkg', { 'promo_code' => {
306                                      op=>'ILIKE',
307                                      value=>$packet->{'promo_code'}
308                                    },
309                                    'disabled'   => '',                  } )
310       ];
311
312     $signup_info->{'error'} = 'Unknown promotional code'
313       unless @{ $signup_info->{'part_pkg'} };
314
315     warn "$me done setting package list via promo_code\n" if $DEBUG > 1;
316   }
317
318   if ( $agentnum ) {
319
320     warn "$me setting agent-specific payment flag\n" if $DEBUG > 1;
321     my $agent = qsearchs('agent', { 'agentnum' => $agentnum } )
322       or return { 'error' => "Self-service agent #$agentnum does not exist" };
323     warn "$me has agent $agent\n" if $DEBUG > 1;
324     my @paybys = @{ $signup_info->{'payby'} };
325     $signup_info->{'hide_payment_fields'} = [];
326
327     my $gatewaynum = $conf->config('selfservice-payment_gateway');
328     my $force_gateway;
329     if ( $gatewaynum ) {
330       $force_gateway = qsearchs('payment_gateway', { gatewaynum => $gatewaynum });
331       warn "using forced gateway #$gatewaynum - " .
332         $force_gateway->gateway_username . '@' . $force_gateway->gateway_module
333         if $DEBUG > 1;
334       die "configured gatewaynum $gatewaynum not found!" if !$force_gateway;
335     }
336     foreach my $payby (@paybys) {
337       warn "$me checking $payby payment fields\n" if $DEBUG > 1;
338       my $hide = 0;
339       if ( FS::payby->realtime($payby) ) {
340         my $gateway = $force_gateway || 
341           $agent->payment_gateway( 'method'  => FS::payby->payby2bop($payby),
342                                    'nofatal' => 1,
343                                  );
344         if ( $gateway && $gateway->gateway_namespace
345                     eq 'Business::OnlineThirdPartyPayment'
346            ) {
347           warn "$me hiding $payby payment fields\n" if $DEBUG > 1;
348           $hide = 1;
349         }
350       }
351       push @{$signup_info->{'hide_payment_fields'}}, $hide;
352     } # foreach $payby
353     warn "$me done setting agent-specific payment flag\n" if $DEBUG > 1;
354
355     warn "$me setting agent-specific package list\n" if $DEBUG > 1;
356     $signup_info->{'part_pkg'} = $signup_info->{'agentnum2part_pkg'}{$agentnum}
357       unless @{ $signup_info->{'part_pkg'} };
358     warn "$me done setting agent-specific package list\n" if $DEBUG > 1;
359
360     warn "$me setting agent-specific adv. source list\n" if $DEBUG > 1;
361     $signup_info->{'part_referral'} =
362       [
363         map { $_->hashref }
364           qsearch( {
365                      'table'     => 'part_referral',
366                      'hashref'   => { 'disabled' => '' },
367                      'extra_sql' => "AND (    agentnum = $agentnum  ".
368                                     "      OR agentnum IS NULL    ) ",
369                    },
370                  )
371       ];
372     warn "$me done setting agent-specific adv. source list\n" if $DEBUG > 1;
373
374     $signup_info->{'agent_name'} = $agent->agent;
375
376     $signup_info->{'company_name'} = $conf->config('company_name', $agentnum);
377
378     #some of the above could probably be cached, too
379
380     my $signup_info_cache_agent = $cache->get("signup_info_cache_agent$agentnum");
381
382     if ( $signup_info_cache_agent ) {
383
384       warn "$me loading cached signup info for agentnum $agentnum\n"
385         if $DEBUG > 1;
386
387     } else {
388
389       warn "$me populating signup info cache for agentnum $agentnum\n"
390         if $DEBUG > 1;
391
392       $signup_info_cache_agent = {
393         #( map { $_ => scalar( $conf->config($_, $agentnum) ) }
394         #  qw( company_name ) ),
395         ( map { $_ => scalar( $conf->config("selfservice-$_", $agentnum ) ) }
396           qw( body_bgcolor box_bgcolor menu_bgcolor ) ),
397         ( map { $_ => join("\n", $conf->config("selfservice-$_", $agentnum ) ) }
398           qw( head body_header body_footer ) ),
399         ( map { $_ => join("\n", $conf->config("signup_server-$_", $agentnum ) ) }
400           qw( terms_of_service ) ),
401
402         ( map { $_ => scalar($conf->exists($_, $agentnum)) } 
403           qw(cust_main-require_phone agent-ship_address) ),
404       };
405
406       if ( $signup_info_cache_agent->{'agent-ship_address'} 
407            && $agent->agent_cust_main ) {
408
409         my $cust_main = $agent->agent_cust_main;
410         my $location = $cust_main->ship_location;
411         $signup_info_cache_agent->{"ship_$_"} = $location->get($_)
412           foreach qw( address1 city county state zip country );
413
414       }
415
416       $cache->set("signup_info_cache_agent$agentnum", $signup_info_cache_agent);
417
418     }
419
420     $signup_info->{$_} = $signup_info_cache_agent->{$_}
421       foreach keys %$signup_info_cache_agent;
422
423   }
424   # else {
425   # delete $signup_info->{'part_pkg'};
426   #}
427
428   warn "$me sorting package list\n" if $DEBUG > 1;
429   $signup_info->{'part_pkg'} = [ sort { $a->{pkg} cmp $b->{pkg} }  # case?
430                                       @{ $signup_info->{'part_pkg'} }
431                                ];
432   warn "$me done sorting package list\n" if $DEBUG > 1;
433
434   if ( exists $packet->{'session_id'} ) {
435     my $agent_signup_info = { %$signup_info };
436     delete $agent_signup_info->{agentnum2part_pkg};
437     $agent_signup_info->{'agent'} = $session->{'agent'};
438     return $agent_signup_info;
439   } 
440   elsif ( exists $packet->{'keys'} ) {
441     my @keys = @{ $packet->{'keys'} };
442     return { map { $_ => $signup_info->{$_} } @keys };
443   }
444   else {
445     return $signup_info;
446   }
447
448 }
449
450 sub domain_select_hash {
451   my $packet = shift;
452
453   my $response = {};
454
455   if ($packet->{pkgpart}) {
456     my $part_pkg = qsearchs('part_pkg' => { 'pkgpart' => $packet->{pkgpart} } );
457     #$packet->{svcpart} = $part_pkg->svcpart('svc_acct')
458     $packet->{svcpart} = $part_pkg->svcpart
459       if $part_pkg;
460   }
461
462   if ($packet->{svcpart}) {
463     my $part_svc = qsearchs('part_svc' => { 'svcpart' => $packet->{svcpart} } );
464     $response->{'domsvc'} = $part_svc->part_svc_column('domsvc')->columnvalue
465       if ($part_svc && $part_svc->part_svc_column('domsvc')->columnflag  eq 'D');
466   }
467
468   $response->{'domains'}
469     = { domain_select_hash FS::svc_acct( map { $_ => $packet->{$_} }
470                                                  qw(svcpart pkgnum)
471                                        ) };
472
473   $response;
474 }
475
476 sub new_customer {
477   my $packet = shift;
478 warn Dumper($packet);
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   my $template_custnum = $conf->config('signup_server-prepaid-template-custnum');
525   my $cust_main;
526   if ( $template_custnum && $packet->{prepaid_shortform} ) {
527
528     my $template_cust = qsearchs('cust_main', { 'custnum' => $template_custnum } );
529     return { 'error' => 'Configuration error' } unless $template_cust;
530     $cust_main = new FS::cust_main ( {
531       'agentnum'      => $agentnum,
532       'refnum'        => $packet->{refnum}
533                          || $conf->config('signup_server-default_refnum'),
534
535       ( map { $_ => $template_cust->$_ } qw( 
536               last first company daytime night fax mobile
537             )
538       ),
539
540       ( map { $_ => $packet->{$_} } qw(
541               ss stateid stateid_state
542
543               payby
544               payinfo paycvv paydate payname paystate paytype
545               paystart_month paystart_year payissue
546               payip
547
548               referral_custnum comments
549             )
550       ),
551
552     } );
553
554     $bill_hash = { $template_cust->bill_location->location_hash };
555     $ship_hash = { $template_cust->ship_location->location_hash };
556
557   } else {
558
559     $cust_main = new FS::cust_main ( {
560       #'custnum'          => '',
561       'agentnum'      => $agentnum,
562       'refnum'        => $packet->{refnum}
563                          || $conf->config('signup_server-default_refnum'),
564
565       map { $_ => $packet->{$_} } qw(
566         last first ss company 
567         daytime night fax mobile
568         stateid stateid_state
569         payby
570         payinfo paycvv paydate payname paystate paytype
571         paystart_month paystart_year payissue
572         payip
573         override_ban_warn
574         referral_custnum comments
575       ),
576
577     } );
578   }
579
580   my $bill_location = FS::cust_location->new($bill_hash);
581   my $ship_location;
582   my $agent = qsearchs('agent', { 'agentnum' => $agentnum } );
583   if ( $conf->exists('agent-ship_address', $agentnum) 
584     && $agent->agent_custnum ) {
585
586     my $agent_cust_main = $agent->agent_cust_main;
587     my $prefix = length($agent_cust_main->ship_last) ? 'ship_' : '';
588     $ship_location = FS::cust_location->new({ 
589         $agent_cust_main->ship_location->location_hash
590     });
591
592   }
593   # we don't have an equivalent of the "same" checkbox in selfservice
594   # so is there a ship address, and if so, is it different from the billing 
595   # address?
596   elsif ( length($ship_hash->{address1}) > 0 and
597           grep { $bill_hash->{$_} ne $ship_hash->{$_} } keys(%$ship_hash)
598          ) {
599
600     $ship_location = FS::cust_location->new( $ship_hash );
601   
602   }
603   else {
604     $ship_location = $bill_location;
605   }
606
607   $cust_main->set('bill_location' => $bill_location);
608   $cust_main->set('ship_location' => $ship_location);
609
610   return { 'error' => "Illegal payment type" }
611     unless grep { $_ eq $packet->{'payby'} }
612                 $conf->config('signup_server-payby');
613
614   if (FS::payby->realtime($packet->{payby})
615     and not $conf->exists('signup_server-third_party_as_card')) {
616     my $payby = $packet->{payby};
617
618     my $agent = qsearchs('agent', { 'agentnum' => $agentnum });
619     return { 'error' => "Unknown reseller" }
620       unless $agent;
621
622     my $gw;
623     my $gatewaynum = $conf->config('selfservice-payment_gateway');
624     if ( $gatewaynum ) {
625       $gw = qsearchs('payment_gateway', { gatewaynum => $gatewaynum });
626       die "configured gatewaynum $gatewaynum not found!" if !$gw;
627     }
628     else {
629       $gw = $agent->payment_gateway( 'method'  => FS::payby->payby2bop($payby),
630                                      'nofatal' => 1,
631                                     );
632     }
633
634     $cust_main->payby('BILL')   # MCRD better?
635       if $gw && $gw->gateway_namespace eq 'Business::OnlineThirdPartyPayment';
636   }
637
638   return { 'error' => "CVV2 is required" }
639     if $cust_main->payby =~ /^(CARD|DCRD)$/
640     && ! $cust_main->paycvv
641     && $conf->exists('signup-require_cvv');
642
643   $cust_main->payinfo($cust_main->daytime)
644     if $cust_main->payby eq 'LECB' && ! $cust_main->payinfo;
645
646   my @invoicing_list = $packet->{'invoicing_list'}
647                          ? split( /\s*\,\s*/, $packet->{'invoicing_list'} )
648                          : ();
649
650   my %insert_options = ();
651
652   my @exempt_groups = grep /\S/, $conf->config('tax-cust_exempt-groups');
653   my @tax_exempt = grep { $packet->{"tax_$_"} eq 'Y' } @exempt_groups;
654   $insert_options{'tax_exemption'} = {
655     map { $_ => $packet->{"tax_$_".'_num'} } @tax_exempt
656   };
657
658   $packet->{'pkgpart'} =~ /^(\d+)$/ or '' =~ /^()$/;
659   my $pkgpart = $1;
660   return { 'error' => 'Please select a package' } unless $pkgpart; #msgcat
661
662   my $part_pkg =
663     qsearchs( 'part_pkg', { 'pkgpart' => $pkgpart } )
664       or return { 'error' => "WARNING: unknown pkgpart: $pkgpart" };
665   my $svcpart = $part_pkg->svcpart($svc_x);
666
667   my $reg_code = '';
668   if ( $packet->{'reg_code'} ) {
669     $reg_code = qsearchs( 'reg_code', { 'code'     => $packet->{'reg_code'},
670                                         'agentnum' => $agentnum,             } )
671       or return { 'error' => 'Unknown registration code' };
672   }
673
674   my $cust_pkg = new FS::cust_pkg ( {
675     #later#'custnum' => $custnum,
676     'pkgpart'    => $packet->{'pkgpart'},
677     'promo_code' => $packet->{'promo_code'},
678     'reg_code'   => $packet->{'reg_code'},
679   } );
680   #my $error = $cust_pkg->check;
681   #return { 'error' => $error } if $error;
682
683   #should be all auto-magic and shit
684   my @svc = ();
685   if ( $svc_x eq 'svc_acct' ) {
686
687     my $svc = new FS::svc_acct {
688       'svcpart'   => $svcpart,
689       map { $_ => $packet->{$_} }
690         qw( username _password sec_phrase popnum domsvc ),
691     };
692
693     my @acct_snarf;
694     my $snarfnum = 1;
695     while (    exists($packet->{"snarf_machine$snarfnum"})
696             && length($packet->{"snarf_machine$snarfnum"}) ) {
697       my $acct_snarf = new FS::acct_snarf ( {
698         'machine'   => $packet->{"snarf_machine$snarfnum"},
699         'protocol'  => $packet->{"snarf_protocol$snarfnum"},
700         'username'  => $packet->{"snarf_username$snarfnum"},
701         '_password' => $packet->{"snarf_password$snarfnum"},
702       } );
703       $snarfnum++;
704       push @acct_snarf, $acct_snarf;
705     }
706     $svc->child_objects( \@acct_snarf );
707     push @svc, $svc;
708
709   } elsif ( $svc_x eq 'svc_phone' ) {
710
711     push @svc, new FS::svc_phone ( {
712       'svcpart' => $svcpart,
713        map { $_ => $packet->{$_} }
714          qw( countrycode phonenum sip_password pin ),
715     } );
716
717   } elsif ( $svc_x eq 'svc_pbx' ) {
718
719     push @svc, new FS::svc_pbx ( {
720         'svcpart' => $svcpart,
721         map { $_ => $packet->{$_} } 
722           qw( id title ),
723         } );
724   
725   } else {
726     die "unknown signup service $svc_x";
727   }
728
729   if ($packet->{'mac_addr'} && $conf->exists('signup_server-mac_addr_svcparts'))
730   {
731
732     my %mac_addr_svcparts = map { $_ => 1 }
733                             $conf->config('signup_server-mac_addr_svcparts');
734     my @pkg_svc = grep { $_->quantity && $mac_addr_svcparts{$_->svcpart} }
735                   $cust_pkg->part_pkg->pkg_svc;
736
737     return { 'error' => 'No service defined to assign mac address' }
738       unless @pkg_svc;
739
740     my $svc = new FS::svc_acct {
741       'svcpart'   => $pkg_svc[0]->svcpart, #multiple matches? alas..
742       'username'  => $packet->{'mac_addr'},
743       '_password' => '', #blank as requested (set passwordmin to 0)
744     };
745
746     push @svc, $svc;
747
748   }
749
750   foreach my $svc ( @svc ) {
751     my $y = $svc->setdefault; # arguably should be in new method
752     return { 'error' => $y } if $y && !ref($y);
753     #$error = $svc->check;
754     #return { 'error' => $error } if $error;
755   }
756
757   #setup a job dependancy to delay provisioning
758   my $placeholder = new FS::queue ( {
759     'job'    => 'FS::ClientAPI::Signup::__placeholder',
760     'status' => 'locked',
761   } );
762   my $error = $placeholder->insert;
763   return { 'error' => $error } if $error;
764
765   use Tie::RefHash;
766   tie my %hash, 'Tie::RefHash';
767   %hash = ( $cust_pkg => \@svc );
768   #msgcat
769   $error = $cust_main->insert(
770     \%hash,
771     \@invoicing_list,
772     'depend_jobnum' => $placeholder->jobnum,
773      %insert_options,
774   );
775   if ( $error ) {
776     my $perror = $placeholder->delete;
777     $error .= " (Additionally, error removing placeholder: $perror)" if $perror;
778     return { 'error' => $error };
779   }
780
781   if ( $conf->exists('signup_server-realtime') ) {
782
783     #warn "$me Billing customer...\n" if $Debug;
784
785     my $bill_error = $cust_main->bill( 'depend_jobnum'=>$placeholder->jobnum );
786     #warn "$me error billing new customer: $bill_error"
787     #  if $bill_error;
788
789     $bill_error = $cust_main->apply_payments_and_credits;
790     #warn "$me error applying payments and credits for".
791     #     " new customer: $bill_error"
792     #  if $bill_error;
793
794     unless ( $packet->{payby} eq 'PREPAY' ) {
795       $bill_error = $cust_main->realtime_collect(
796          method        => FS::payby->payby2bop( $packet->{payby} ),
797          depend_jobnum => $placeholder->jobnum,
798          selfservice   => 1,
799       );
800       #warn "$me error collecting from new customer: $bill_error"
801       #  if $bill_error;
802     }
803
804     if ($bill_error && ref($bill_error) eq 'HASH') {
805       return { 'error' => '_collect',
806                ( map { $_ => $bill_error->{$_} }
807                  qw(popup_url reference collectitems)
808                ),
809                amount => $cust_main->balance,
810              };
811     }
812
813     $bill_error = $cust_main->apply_payments_and_credits;
814     #warn "$me error applying payments and credits for".
815     #     " new customer: $bill_error"
816     #  if $bill_error;
817
818     if ( $cust_main->balance > 0 ) {
819
820       #this makes sense.  credit is "un-doing" the invoice
821       $cust_main->credit( $cust_main->balance, 'signup server decline',
822                           'reason_type' => $conf->config('signup_credit_type'),
823                         );
824       $cust_main->apply_credits;
825
826       #should check list for errors...
827       #$cust_main->suspend;
828       local $FS::svc_Common::noexport_hack = 1;
829       $cust_main->cancel('quiet'=>1);
830
831       my $perror = $placeholder->depended_delete;
832       warn "error removing provisioning jobs after decline: $perror" if $perror;
833       unless ( $perror ) {
834         $perror = $placeholder->delete;
835         warn "error removing placeholder after decline: $perror" if $perror;
836       }
837
838       return { 'error' => '_decline' };
839     }
840
841   }
842
843   if ( $reg_code ) {
844     $error = $reg_code->delete;
845     return { 'error' => $error } if $error;
846   }
847
848   $error = $placeholder->delete;
849   return { 'error' => $error } if $error;
850
851   if ( $conf->exists('signup-duplicate_cc-warn_hours') ) {
852     my $hours = $conf->config('signup-duplicate_cc-warn_hours');
853     my $ban = new FS::banned_pay $cust_main->_new_banned_pay_hashref;
854     $ban->end_date( int( time + $hours*3600 ) );
855     $ban->bantype('warn');
856     $ban->reason('signup-duplicate_cc-warn_hours');
857     $error = $ban->insert;
858     warn "WARNING: error inserting temporary banned_pay for ".
859          " signup-duplicate_cc-warn_hours (proceeding anyway): $error"
860       if $error;
861   }
862
863   my %return = ( 'error'          => '',
864                  'signup_service' => $svc_x,
865                  'custnum'        => $cust_main->custnum,
866                );
867
868   if ( $svc[0] ) {
869
870     $return{'svcnum'} = $svc[0]->svcnum;
871
872     if ( $svc_x eq 'svc_acct' ) {
873       $return{$_} = $svc[0]->$_() for qw( username _password );
874     } elsif ( $svc_x eq 'svc_phone' ) {
875       $return{$_} = $svc[0]->$_() for qw(countrycode phonenum sip_password pin);
876     } elsif ( $svc_x eq 'svc_pbx' ) {
877       #$return{$_} = $svc[0]->$_() for qw( ) #nothing yet
878      } else {
879       return {'error' => "configuration error: unknown signup service $svc_x"};
880       #die "unknown signup service $svc_x";
881       # return an error that's visible to someone somewhere
882     }
883
884   }
885
886   return \%return;
887
888 }
889
890 sub capture_payment {
891   my $packet = shift;
892
893   warn "$me capture_payment called on $packet\n" if $DEBUG;
894
895   ###
896   # identify processor/gateway from called back URL
897   ###
898
899   my $conf = new FS::Conf;
900
901   my $payment_gateway;
902   if ( my $gwnum = $conf->config('selfservice-payment_gateway') ) {
903     $payment_gateway = qsearchs('payment_gateway', { 'gatewaynum' => $gwnum })
904       or die "configured gatewaynum $gwnum not found!";
905   }
906   else {
907     my $url = $packet->{url};
908
909     $payment_gateway = qsearchs('payment_gateway', 
910         { 'gateway_callback_url' => popurl(0, $url) } 
911       );
912     if (!$payment_gateway) { 
913
914       my ( $processor, $login, $password, $action, @bop_options ) =
915         $conf->config('business-onlinepayment');
916       $action ||= 'normal authorization';
917       pop @bop_options if scalar(@bop_options) % 2 && $bop_options[-1] =~ /^\s*$/;
918       die "No real-time processor is enabled - ".
919           "did you set the business-onlinepayment configuration value?\n"
920         unless $processor;
921
922       $payment_gateway = new FS::payment_gateway( {
923         gateway_namespace => $conf->config('business-onlinepayment-namespace'),
924         gateway_module    => $processor,
925         gateway_username  => $login,
926         gateway_password  => $password,
927         gateway_action    => $action,
928         options   => [ ( @bop_options ) ],
929       });
930     }
931   }
932  
933   die "No real-time third party processor is enabled - ".
934       "did you set the business-onlinepayment configuration value?\n*"
935     unless $payment_gateway->gateway_namespace eq 'Business::OnlineThirdPartyPayment';
936
937   ###
938   # locate pending transaction
939   ###
940
941   eval "use Business::OnlineThirdPartyPayment";
942   die $@ if $@;
943
944   my $transaction =
945     new Business::OnlineThirdPartyPayment( $payment_gateway->gateway_module,
946                                            @{ [ $payment_gateway->options ] },
947                                          );
948
949   my $paypendingnum = $transaction->reference($packet->{data});
950
951   my $cust_pay_pending =
952     qsearchs('cust_pay_pending', { paypendingnum => $paypendingnum } );
953
954   unless ($cust_pay_pending) {
955     my $bill_error = "No payment is being processed with id $paypendingnum".
956                      "; Transaction aborted.";
957     return { error => '_decline', bill_error => $bill_error };
958   }
959
960   if ($cust_pay_pending->status ne 'thirdparty') {
961     my $bill_error = "Payment with id $paypendingnum is not thirdparty, but ".
962                      $cust_pay_pending->status.  "; Transaction aborted.";
963     return { error => '_decline', bill_error => $bill_error };
964   }
965
966   my $cust_main = $cust_pay_pending->cust_main;
967   if ( $packet->{cancel} ) {
968     # the user has chosen not to make this payment
969     # (probably should be a separate API call, but I don't want to duplicate
970     # all of the above...which should eventually go away)
971     my $error = $cust_pay_pending->delete;
972     # don't show any errors related to this; they're not meaningful
973     warn "error canceling pending payment $paypendingnum: $error\n" if $error;
974     return { 'error'      => '_cancel',
975              'session_id' => $cust_pay_pending->session_id };
976   } else {
977     # create the payment
978     my $bill_error =
979       $cust_main->realtime_botpp_capture( $cust_pay_pending, 
980         %{$packet->{data}},
981         apply => 1,
982     );
983
984     return { 'error'      => ( $bill_error->{bill_error} ? '_decline' : '' ),
985              %$bill_error,
986            };
987   }
988
989 }
990
991 1;