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