57091c4fe38d66ca122df96d17b202606bfdc54a
[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       'stateid_enabled'    => $conf->exists('show_stateid'),
178       'paystate_enabled'   => $conf->exists('show_bankstate'),
179       'ship_enabled'       => 1,
180       'msgcat'             => $msgcat,
181       'label'              => $label,
182       'statedefault'       => scalar($conf->config('statedefault')) || 'CA',
183       'countrydefault'     => scalar($conf->config('countrydefault')) || 'US',
184       'refnum'             => scalar($conf->config('signup_server-default_refnum')),
185       'signup_service'     => $svc_x,
186       'company_name'       => scalar($conf->config('company_name')),
187       #per-agent?
188       'logo'               => scalar($conf->config_binary('logo.png')),
189       'prepaid_template_custnum' => $conf->exists('signup_server-prepaid-template-custnum'),
190     };
191
192     $cache->set('signup_info_cache', $signup_info_cache);
193
194   }
195
196   my $signup_info = { %$signup_info_cache };
197   warn "$me signup info loaded\n" if $DEBUG > 1;
198   warn Dumper($signup_info). "\n" if $DEBUG > 2;
199
200   my @addl = qw( signup_server-classnum2 signup_server-classnum3 );
201
202   if ( grep { $conf->exists($_) } @addl ) {
203   
204     $signup_info->{optional_packages} = [];
205
206     foreach my $addl ( @addl ) {
207
208       warn "$me adding optional package info\n" if $DEBUG > 1;
209
210       my $classnum = $conf->config($addl) or next;
211
212       my @pkgs = map { {
213                          'freq_pretty' => $_->freq_pretty,
214                          'options'     => { $_->options },
215                          %{ $_->hashref }
216                        };
217                      }
218                      qsearch( 'part_pkg', { classnum => $classnum } );
219
220       push @{$signup_info->{optional_packages}}, \@pkgs;
221
222       warn "$me done adding opt. package info for $classnum\n" if $DEBUG > 1;
223
224     }
225
226   }
227
228   my $agentnum = $packet->{'agentnum'}
229                  || $conf->config('signup_server-default_agentnum');
230   $agentnum =~ /^(\d*)$/ or die "illegal agentnum";
231   $agentnum = $1;
232
233   my $session = '';
234   if ( exists $packet->{'session_id'} ) {
235
236     warn "$me loading agent session\n" if $DEBUG > 1;
237     my $cache = new FS::ClientAPI_SessionCache( {
238       'namespace' => 'FS::ClientAPI::Agent',
239     } );
240     $session = $cache->get($packet->{'session_id'});
241     if ( $session ) {
242       $agentnum = $session->{'agentnum'};
243     } else {
244       return { 'error' => "Can't resume session" }; #better error message
245     }
246     warn "$me done loading agent session\n" if $DEBUG > 1;
247
248   } elsif ( exists $packet->{'customer_session_id'} ) {
249
250     warn "$me loading customer session\n" if $DEBUG > 1;
251     my $cache = new FS::ClientAPI_SessionCache( {
252       'namespace' => 'FS::ClientAPI::MyAccount',
253     } );
254     $session = $cache->get($packet->{'customer_session_id'});
255     if ( $session ) {
256       my $custnum = $session->{'custnum'};
257       my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum });
258       return { 'error' => "Can't find your customer record" } unless $cust_main;
259       $agentnum = $cust_main->agentnum;
260     } else {
261       return { 'error' => "Can't resume session" }; #better error message
262     }
263     warn "$me done loading customer session\n" if $DEBUG > 1;
264
265   }
266
267   $signup_info->{'part_pkg'} = [];
268
269   if ( $packet->{'reg_code'} ) {
270
271     warn "$me setting package list via reg_code\n" if $DEBUG > 1;
272
273     $signup_info->{'part_pkg'} = 
274       [ map { { 'payby'       => [ $_->payby ],
275                 'freq_pretty' => $_->freq_pretty,
276                 'options'     => { $_->options },
277                 %{$_->hashref}
278               };
279             }
280           grep { $_->svcpart($svc_x) }
281           map { $_->part_pkg }
282             qsearchs( 'reg_code', { 'code'     => $packet->{'reg_code'},
283                                     'agentnum' => $agentnum,              } )
284
285       ];
286
287     $signup_info->{'error'} = 'Unknown registration code'
288       unless @{ $signup_info->{'part_pkg'} };
289
290     warn "$me done setting package list via reg_code\n" if $DEBUG > 1;
291
292   } elsif ( $packet->{'promo_code'} ) {
293
294     warn "$me setting package list via promo_code\n" if $DEBUG > 1;
295
296     $signup_info->{'part_pkg'} =
297       [ map { { 'payby'   => [ $_->payby ],
298                 'freq_pretty' => $_->freq_pretty,
299                 'options'     => { $_->options },
300                 %{$_->hashref}
301             } }
302           grep { $_->svcpart($svc_x) }
303             qsearch( 'part_pkg', { 'promo_code' => {
304                                      op=>'ILIKE',
305                                      value=>$packet->{'promo_code'}
306                                    },
307                                    'disabled'   => '',                  } )
308       ];
309
310     $signup_info->{'error'} = 'Unknown promotional code'
311       unless @{ $signup_info->{'part_pkg'} };
312
313     warn "$me done setting package list via promo_code\n" if $DEBUG > 1;
314   }
315
316   if ( $agentnum ) {
317
318     warn "$me setting agent-specific payment flag\n" if $DEBUG > 1;
319     my $agent = qsearchs('agent', { 'agentnum' => $agentnum } )
320       or return { 'error' => "Self-service agent #$agentnum does not exist" };
321     warn "$me has agent $agent\n" if $DEBUG > 1;
322     my @paybys = @{ $signup_info->{'payby'} };
323     $signup_info->{'hide_payment_fields'} = [];
324
325     my $gatewaynum = $conf->config('selfservice-payment_gateway');
326     my $force_gateway;
327     if ( $gatewaynum ) {
328       $force_gateway = qsearchs('payment_gateway', { gatewaynum => $gatewaynum });
329       warn "using forced gateway #$gatewaynum - " .
330         $force_gateway->gateway_username . '@' . $force_gateway->gateway_module
331         if $DEBUG > 1;
332       die "configured gatewaynum $gatewaynum not found!" if !$force_gateway;
333     }
334     foreach my $payby (@paybys) {
335       warn "$me checking $payby payment fields\n" if $DEBUG > 1;
336       my $hide = 0;
337       if ( FS::payby->realtime($payby) ) {
338         my $gateway = $force_gateway || 
339           $agent->payment_gateway( 'method'  => FS::payby->payby2bop($payby),
340                                    'nofatal' => 1,
341                                  );
342         if ( $gateway && $gateway->gateway_namespace
343                     eq 'Business::OnlineThirdPartyPayment'
344            ) {
345           warn "$me hiding $payby payment fields\n" if $DEBUG > 1;
346           $hide = 1;
347         }
348       }
349       push @{$signup_info->{'hide_payment_fields'}}, $hide;
350     } # foreach $payby
351     warn "$me done setting agent-specific payment flag\n" if $DEBUG > 1;
352
353     warn "$me setting agent-specific package list\n" if $DEBUG > 1;
354     $signup_info->{'part_pkg'} = $signup_info->{'agentnum2part_pkg'}{$agentnum}
355       unless @{ $signup_info->{'part_pkg'} };
356     warn "$me done setting agent-specific package list\n" if $DEBUG > 1;
357
358     warn "$me setting agent-specific adv. source list\n" if $DEBUG > 1;
359     $signup_info->{'part_referral'} =
360       [
361         map { $_->hashref }
362           qsearch( {
363                      'table'     => 'part_referral',
364                      'hashref'   => { 'disabled' => '' },
365                      'extra_sql' => "AND (    agentnum = $agentnum  ".
366                                     "      OR agentnum IS NULL    ) ",
367                    },
368                  )
369       ];
370     warn "$me done setting agent-specific adv. source list\n" if $DEBUG > 1;
371
372     $signup_info->{'agent_name'} = $agent->agent;
373
374     $signup_info->{'company_name'} = $conf->config('company_name', $agentnum);
375
376     #some of the above could probably be cached, too
377
378     my $signup_info_cache_agent = $cache->get("signup_info_cache_agent$agentnum");
379
380     if ( $signup_info_cache_agent ) {
381
382       warn "$me loading cached signup info for agentnum $agentnum\n"
383         if $DEBUG > 1;
384
385     } else {
386
387       warn "$me populating signup info cache for agentnum $agentnum\n"
388         if $DEBUG > 1;
389
390       $signup_info_cache_agent = {
391         #( map { $_ => scalar( $conf->config($_, $agentnum) ) }
392         #  qw( company_name ) ),
393         ( map { $_ => scalar( $conf->config("selfservice-$_", $agentnum ) ) }
394           qw( body_bgcolor box_bgcolor menu_bgcolor ) ),
395         ( map { $_ => join("\n", $conf->config("selfservice-$_", $agentnum ) ) }
396           qw( head body_header body_footer ) ),
397         ( map { $_ => join("\n", $conf->config("signup_server-$_", $agentnum ) ) }
398           qw( terms_of_service ) ),
399
400         ( map { $_ => scalar($conf->exists($_, $agentnum)) } 
401           qw(cust_main-require_phone agent-ship_address) ),
402       };
403
404       if ( $signup_info_cache_agent->{'agent-ship_address'} 
405            && $agent->agent_cust_main ) {
406
407         my $cust_main = $agent->agent_cust_main;
408         my $location = $cust_main->ship_location;
409         $signup_info_cache_agent->{"ship_$_"} = $location->get($_)
410           foreach qw( address1 city county state zip country );
411
412       }
413
414       $cache->set("signup_info_cache_agent$agentnum", $signup_info_cache_agent);
415
416     }
417
418     $signup_info->{$_} = $signup_info_cache_agent->{$_}
419       foreach keys %$signup_info_cache_agent;
420
421   }
422   # else {
423   # delete $signup_info->{'part_pkg'};
424   #}
425
426   warn "$me sorting package list\n" if $DEBUG > 1;
427   $signup_info->{'part_pkg'} = [ sort { $a->{pkg} cmp $b->{pkg} }  # case?
428                                       @{ $signup_info->{'part_pkg'} }
429                                ];
430   warn "$me done sorting package list\n" if $DEBUG > 1;
431
432   if ( exists $packet->{'session_id'} ) {
433     my $agent_signup_info = { %$signup_info };
434     delete $agent_signup_info->{agentnum2part_pkg};
435     $agent_signup_info->{'agent'} = $session->{'agent'};
436     return $agent_signup_info;
437   } 
438   elsif ( exists $packet->{'keys'} ) {
439     my @keys = @{ $packet->{'keys'} };
440     return { map { $_ => $signup_info->{$_} } @keys };
441   }
442   else {
443     return $signup_info;
444   }
445
446 }
447
448 sub domain_select_hash {
449   my $packet = shift;
450
451   my $response = {};
452
453   if ($packet->{pkgpart}) {
454     my $part_pkg = qsearchs('part_pkg' => { 'pkgpart' => $packet->{pkgpart} } );
455     #$packet->{svcpart} = $part_pkg->svcpart('svc_acct')
456     $packet->{svcpart} = $part_pkg->svcpart
457       if $part_pkg;
458   }
459
460   if ($packet->{svcpart}) {
461     my $part_svc = qsearchs('part_svc' => { 'svcpart' => $packet->{svcpart} } );
462     $response->{'domsvc'} = $part_svc->part_svc_column('domsvc')->columnvalue
463       if ($part_svc && $part_svc->part_svc_column('domsvc')->columnflag  eq 'D');
464   }
465
466   $response->{'domains'}
467     = { domain_select_hash FS::svc_acct( map { $_ => $packet->{$_} }
468                                                  qw(svcpart pkgnum)
469                                        ) };
470
471   $response;
472 }
473
474 sub new_customer {
475   my $packet = shift;
476
477   my $conf = new FS::Conf;
478   my $svc_x = $conf->config('signup_server-service') || 'svc_acct';
479
480   if ( $svc_x eq 'svc_acct' ) {
481   
482     #things that aren't necessary in base class, but are for signup server
483       #return "Passwords don't match"
484       #  if $hashref->{'_password'} ne $hashref->{'_password2'}
485     return { 'error' => gettext('empty_password') }
486       unless length($packet->{'_password'});
487     # a bit inefficient for large numbers of pops
488     return { 'error' => gettext('no_access_number_selected') }
489       unless $packet->{'popnum'} || !scalar(qsearch('svc_acct_pop',{} ));
490
491   }
492   elsif ( $svc_x eq 'svc_pbx' ) {
493     #possibly some validation will be needed
494   }
495
496   my $agentnum;
497   if ( exists $packet->{'session_id'} ) {
498     my $cache = new FS::ClientAPI_SessionCache( {
499       'namespace' => 'FS::ClientAPI::Agent',
500     } );
501     my $session = $cache->get($packet->{'session_id'});
502     if ( $session ) {
503       $agentnum = $session->{'agentnum'};
504     } else {
505       return { 'error' => "Can't resume session" }; #better error message
506     }
507   } else {
508     $agentnum = $packet->{agentnum}
509                 || $conf->config('signup_server-default_agentnum');
510   }
511
512   my ($bill_hash, $ship_hash);
513   foreach my $f (FS::cust_main->location_fields) {
514     # avoid having to change this in front-end code
515     $bill_hash->{$f} = $packet->{"bill_$f"} || $packet->{$f};
516     $ship_hash->{$f} = $packet->{"ship_$f"};
517   }
518
519   #shares some stuff with htdocs/edit/process/cust_main.cgi... take any
520   # common that are still here and library them.
521   my $template_custnum = $conf->config('signup_server-prepaid-template-custnum');
522   my $cust_main;
523   if ( $template_custnum && $packet->{prepaid_shortform} ) {
524
525     my $template_cust = qsearchs('cust_main', { 'custnum' => $template_custnum } );
526     return { 'error' => 'Configuration error' } unless $template_cust;
527     $cust_main = new FS::cust_main ( {
528       'agentnum'      => $agentnum,
529       'refnum'        => $packet->{refnum}
530                          || $conf->config('signup_server-default_refnum'),
531
532       ( map { $_ => $template_cust->$_ } qw( 
533               last first company daytime night fax 
534             )
535       ),
536
537       ( map { $_ => $packet->{$_} } qw(
538               ss stateid stateid_state
539
540               payby
541               payinfo paycvv paydate payname paystate paytype
542               paystart_month paystart_year payissue
543               payip
544
545               referral_custnum comments
546             )
547       ),
548
549     } );
550
551     $bill_hash = { $template_cust->bill_location->location_hash };
552     $ship_hash = { $template_cust->ship_location->location_hash };
553
554   } else {
555
556     $cust_main = new FS::cust_main ( {
557       #'custnum'          => '',
558       'agentnum'      => $agentnum,
559       'refnum'        => $packet->{refnum}
560                          || $conf->config('signup_server-default_refnum'),
561
562       map { $_ => $packet->{$_} } qw(
563         last first ss company 
564         daytime night fax stateid stateid_state
565         payby
566         payinfo paycvv paydate payname paystate paytype
567         paystart_month paystart_year payissue
568         payip
569         override_ban_warn
570         referral_custnum comments
571       ),
572
573     } );
574   }
575
576   my $bill_location = FS::cust_location->new($bill_hash);
577   my $ship_location;
578   my $agent = qsearchs('agent', { 'agentnum' => $agentnum } );
579   if ( $conf->exists('agent-ship_address', $agentnum) 
580     && $agent->agent_custnum ) {
581
582     my $agent_cust_main = $agent->agent_cust_main;
583     my $prefix = length($agent_cust_main->ship_last) ? 'ship_' : '';
584     $ship_location = FS::cust_location->new({ 
585         $agent_cust_main->ship_location->location_hash
586     });
587
588   }
589   # we don't have an equivalent of the "same" checkbox in selfservice
590   # so is there a ship address, and if so, is it different from the billing 
591   # address?
592   elsif ( length($ship_hash->{address1}) > 0 and
593           grep { $bill_hash->{$_} ne $ship_hash->{$_} } keys(%$ship_hash)
594          ) {
595
596     $ship_location = FS::cust_location->new( $ship_hash );
597   
598   }
599   else {
600     $ship_location = $bill_location;
601   }
602
603   $cust_main->set('bill_location' => $bill_location);
604   $cust_main->set('ship_location' => $ship_location);
605
606   return { 'error' => "Illegal payment type" }
607     unless grep { $_ eq $packet->{'payby'} }
608                 $conf->config('signup_server-payby');
609
610   if (FS::payby->realtime($packet->{payby})
611     and not $conf->exists('signup_server-third_party_as_card')) {
612     my $payby = $packet->{payby};
613
614     my $agent = qsearchs('agent', { 'agentnum' => $agentnum });
615     return { 'error' => "Unknown reseller" }
616       unless $agent;
617
618     my $gw;
619     my $gatewaynum = $conf->config('selfservice-payment_gateway');
620     if ( $gatewaynum ) {
621       $gw = qsearchs('payment_gateway', { gatewaynum => $gatewaynum });
622       die "configured gatewaynum $gatewaynum not found!" if !$gw;
623     }
624     else {
625       $gw = $agent->payment_gateway( 'method'  => FS::payby->payby2bop($payby),
626                                      'nofatal' => 1,
627                                     );
628     }
629
630     $cust_main->payby('BILL')   # MCRD better?
631       if $gw && $gw->gateway_namespace eq 'Business::OnlineThirdPartyPayment';
632   }
633
634   $cust_main->payinfo($cust_main->daytime)
635     if $cust_main->payby eq 'LECB' && ! $cust_main->payinfo;
636
637   my @invoicing_list = $packet->{'invoicing_list'}
638                          ? split( /\s*\,\s*/, $packet->{'invoicing_list'} )
639                          : ();
640
641   $packet->{'pkgpart'} =~ /^(\d+)$/ or '' =~ /^()$/;
642   my $pkgpart = $1;
643   return { 'error' => 'Please select a package' } unless $pkgpart; #msgcat
644
645   my $part_pkg =
646     qsearchs( 'part_pkg', { 'pkgpart' => $pkgpart } )
647       or return { 'error' => "WARNING: unknown pkgpart: $pkgpart" };
648   my $svcpart = $part_pkg->svcpart($svc_x);
649
650   my $reg_code = '';
651   if ( $packet->{'reg_code'} ) {
652     $reg_code = qsearchs( 'reg_code', { 'code'     => $packet->{'reg_code'},
653                                         'agentnum' => $agentnum,             } )
654       or return { 'error' => 'Unknown registration code' };
655   }
656
657   my $cust_pkg = new FS::cust_pkg ( {
658     #later#'custnum' => $custnum,
659     'pkgpart'    => $packet->{'pkgpart'},
660     'promo_code' => $packet->{'promo_code'},
661     'reg_code'   => $packet->{'reg_code'},
662   } );
663   #my $error = $cust_pkg->check;
664   #return { 'error' => $error } if $error;
665
666   #should be all auto-magic and shit
667   my @svc = ();
668   if ( $svc_x eq 'svc_acct' ) {
669
670     my $svc = new FS::svc_acct {
671       'svcpart'   => $svcpart,
672       map { $_ => $packet->{$_} }
673         qw( username _password sec_phrase popnum domsvc ),
674     };
675
676     my @acct_snarf;
677     my $snarfnum = 1;
678     while (    exists($packet->{"snarf_machine$snarfnum"})
679             && length($packet->{"snarf_machine$snarfnum"}) ) {
680       my $acct_snarf = new FS::acct_snarf ( {
681         'machine'   => $packet->{"snarf_machine$snarfnum"},
682         'protocol'  => $packet->{"snarf_protocol$snarfnum"},
683         'username'  => $packet->{"snarf_username$snarfnum"},
684         '_password' => $packet->{"snarf_password$snarfnum"},
685       } );
686       $snarfnum++;
687       push @acct_snarf, $acct_snarf;
688     }
689     $svc->child_objects( \@acct_snarf );
690     push @svc, $svc;
691
692   } elsif ( $svc_x eq 'svc_phone' ) {
693
694     push @svc, new FS::svc_phone ( {
695       'svcpart' => $svcpart,
696        map { $_ => $packet->{$_} }
697          qw( countrycode phonenum sip_password pin ),
698     } );
699
700   } elsif ( $svc_x eq 'svc_pbx' ) {
701
702     push @svc, new FS::svc_pbx ( {
703         'svcpart' => $svcpart,
704         map { $_ => $packet->{$_} } 
705           qw( id title ),
706         } );
707   
708   } else {
709     die "unknown signup service $svc_x";
710   }
711
712   if ($packet->{'mac_addr'} && $conf->exists('signup_server-mac_addr_svcparts'))
713   {
714
715     my %mac_addr_svcparts = map { $_ => 1 }
716                             $conf->config('signup_server-mac_addr_svcparts');
717     my @pkg_svc = grep { $_->quantity && $mac_addr_svcparts{$_->svcpart} }
718                   $cust_pkg->part_pkg->pkg_svc;
719
720     return { 'error' => 'No service defined to assign mac address' }
721       unless @pkg_svc;
722
723     my $svc = new FS::svc_acct {
724       'svcpart'   => $pkg_svc[0]->svcpart, #multiple matches? alas..
725       'username'  => $packet->{'mac_addr'},
726       '_password' => '', #blank as requested (set passwordmin to 0)
727     };
728
729     push @svc, $svc;
730
731   }
732
733   foreach my $svc ( @svc ) {
734     my $y = $svc->setdefault; # arguably should be in new method
735     return { 'error' => $y } if $y && !ref($y);
736     #$error = $svc->check;
737     #return { 'error' => $error } if $error;
738   }
739
740   #setup a job dependancy to delay provisioning
741   my $placeholder = new FS::queue ( {
742     'job'    => 'FS::ClientAPI::Signup::__placeholder',
743     'status' => 'locked',
744   } );
745   my $error = $placeholder->insert;
746   return { 'error' => $error } if $error;
747
748   use Tie::RefHash;
749   tie my %hash, 'Tie::RefHash';
750   %hash = ( $cust_pkg => \@svc );
751   #msgcat
752   $error = $cust_main->insert(
753     \%hash,
754     \@invoicing_list,
755     'depend_jobnum' => $placeholder->jobnum,
756   );
757   if ( $error ) {
758     my $perror = $placeholder->delete;
759     $error .= " (Additionally, error removing placeholder: $perror)" if $perror;
760     return { 'error' => $error };
761   }
762
763   if ( $conf->exists('signup_server-realtime') ) {
764
765     #warn "$me Billing customer...\n" if $Debug;
766
767     my $bill_error = $cust_main->bill( 'depend_jobnum'=>$placeholder->jobnum );
768     #warn "$me error billing new customer: $bill_error"
769     #  if $bill_error;
770
771     $bill_error = $cust_main->apply_payments_and_credits;
772     #warn "$me error applying payments and credits for".
773     #     " new customer: $bill_error"
774     #  if $bill_error;
775
776     unless ( $packet->{payby} eq 'PREPAY' ) {
777       $bill_error = $cust_main->realtime_collect(
778          method        => FS::payby->payby2bop( $packet->{payby} ),
779          depend_jobnum => $placeholder->jobnum,
780          selfservice   => 1,
781       );
782       #warn "$me error collecting from new customer: $bill_error"
783       #  if $bill_error;
784     }
785
786     if ($bill_error && ref($bill_error) eq 'HASH') {
787       return { 'error' => '_collect',
788                ( map { $_ => $bill_error->{$_} }
789                  qw(popup_url reference collectitems)
790                ),
791                amount => $cust_main->balance,
792              };
793     }
794
795     $bill_error = $cust_main->apply_payments_and_credits;
796     #warn "$me error applying payments and credits for".
797     #     " new customer: $bill_error"
798     #  if $bill_error;
799
800     if ( $cust_main->balance > 0 ) {
801
802       #this makes sense.  credit is "un-doing" the invoice
803       $cust_main->credit( $cust_main->balance, 'signup server decline',
804                           'reason_type' => $conf->config('signup_credit_type'),
805                         );
806       $cust_main->apply_credits;
807
808       #should check list for errors...
809       #$cust_main->suspend;
810       local $FS::svc_Common::noexport_hack = 1;
811       $cust_main->cancel('quiet'=>1);
812
813       my $perror = $placeholder->depended_delete;
814       warn "error removing provisioning jobs after decline: $perror" if $perror;
815       unless ( $perror ) {
816         $perror = $placeholder->delete;
817         warn "error removing placeholder after decline: $perror" if $perror;
818       }
819
820       return { 'error' => '_decline' };
821     }
822
823   }
824
825   if ( $reg_code ) {
826     $error = $reg_code->delete;
827     return { 'error' => $error } if $error;
828   }
829
830   $error = $placeholder->delete;
831   return { 'error' => $error } if $error;
832
833   if ( $conf->exists('signup-duplicate_cc-warn_hours') ) {
834     my $hours = $conf->config('signup-duplicate_cc-warn_hours');
835     my $ban = new FS::banned_pay $cust_main->_new_banned_pay_hashref;
836     $ban->end_date( int( time + $hours*3600 ) );
837     $ban->bantype('warn');
838     $ban->reason('signup-duplicate_cc-warn_hours');
839     $error = $ban->insert;
840     warn "WARNING: error inserting temporary banned_pay for ".
841          " signup-duplicate_cc-warn_hours (proceeding anyway): $error"
842       if $error;
843   }
844
845   my %return = ( 'error'          => '',
846                  'signup_service' => $svc_x,
847                  'custnum'        => $cust_main->custnum,
848                );
849
850   if ( $svc[0] ) {
851
852     $return{'svcnum'} = $svc[0]->svcnum;
853
854     if ( $svc_x eq 'svc_acct' ) {
855       $return{$_} = $svc[0]->$_() for qw( username _password );
856     } elsif ( $svc_x eq 'svc_phone' ) {
857       $return{$_} = $svc[0]->$_() for qw(countrycode phonenum sip_password pin);
858     } elsif ( $svc_x eq 'svc_pbx' ) {
859       #$return{$_} = $svc[0]->$_() for qw( ) #nothing yet
860      } else {
861       return {'error' => "configuration error: unknown signup service $svc_x"};
862       #die "unknown signup service $svc_x";
863       # return an error that's visible to someone somewhere
864     }
865
866   }
867
868   return \%return;
869
870 }
871
872 sub capture_payment {
873   my $packet = shift;
874
875   warn "$me capture_payment called on $packet\n" if $DEBUG;
876
877   ###
878   # identify processor/gateway from called back URL
879   ###
880
881   my $conf = new FS::Conf;
882
883   my $payment_gateway;
884   if ( my $gwnum = $conf->config('selfservice-payment_gateway') ) {
885     $payment_gateway = qsearchs('payment_gateway', { 'gatewaynum' => $gwnum })
886       or die "configured gatewaynum $gwnum not found!";
887   }
888   else {
889     my $url = $packet->{url};
890
891     $payment_gateway = qsearchs('payment_gateway', 
892         { 'gateway_callback_url' => popurl(0, $url) } 
893       );
894     if (!$payment_gateway) { 
895
896       my ( $processor, $login, $password, $action, @bop_options ) =
897         $conf->config('business-onlinepayment');
898       $action ||= 'normal authorization';
899       pop @bop_options if scalar(@bop_options) % 2 && $bop_options[-1] =~ /^\s*$/;
900       die "No real-time processor is enabled - ".
901           "did you set the business-onlinepayment configuration value?\n"
902         unless $processor;
903
904       $payment_gateway = new FS::payment_gateway( {
905         gateway_namespace => $conf->config('business-onlinepayment-namespace'),
906         gateway_module    => $processor,
907         gateway_username  => $login,
908         gateway_password  => $password,
909         gateway_action    => $action,
910         options   => [ ( @bop_options ) ],
911       });
912     }
913   }
914  
915   die "No real-time third party processor is enabled - ".
916       "did you set the business-onlinepayment configuration value?\n*"
917     unless $payment_gateway->gateway_namespace eq 'Business::OnlineThirdPartyPayment';
918
919   ###
920   # locate pending transaction
921   ###
922
923   eval "use Business::OnlineThirdPartyPayment";
924   die $@ if $@;
925
926   my $transaction =
927     new Business::OnlineThirdPartyPayment( $payment_gateway->gateway_module,
928                                            @{ [ $payment_gateway->options ] },
929                                          );
930
931   my $paypendingnum = $transaction->reference($packet->{data});
932
933   my $cust_pay_pending =
934     qsearchs('cust_pay_pending', { paypendingnum => $paypendingnum } );
935
936   unless ($cust_pay_pending) {
937     my $bill_error = "No payment is being processed with id $paypendingnum".
938                      "; Transaction aborted.";
939     return { error => '_decline', bill_error => $bill_error };
940   }
941
942   if ($cust_pay_pending->status ne 'thirdparty') {
943     my $bill_error = "Payment with id $paypendingnum is not thirdparty, but ".
944                      $cust_pay_pending->status.  "; Transaction aborted.";
945     return { error => '_decline', bill_error => $bill_error };
946   }
947
948   my $cust_main = $cust_pay_pending->cust_main;
949   if ( $packet->{cancel} ) {
950     # the user has chosen not to make this payment
951     # (probably should be a separate API call, but I don't want to duplicate
952     # all of the above...which should eventually go away)
953     my $error = $cust_pay_pending->delete;
954     # don't show any errors related to this; they're not meaningful
955     warn "error canceling pending payment $paypendingnum: $error\n" if $error;
956     return { 'error'      => '_cancel',
957              'session_id' => $cust_pay_pending->session_id };
958   } else {
959     # create the payment
960     my $bill_error =
961       $cust_main->realtime_botpp_capture( $cust_pay_pending, 
962         %{$packet->{data}},
963         apply => 1,
964     );
965
966     return { 'error'      => ( $bill_error->{bill_error} ? '_decline' : '' ),
967              %$bill_error,
968            };
969   }
970
971 }
972
973 1;