per-agent agent-ship_address config, #6678
[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 );
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 $prefix = length($cust_main->ship_last) ? 'ship_' : '';
409         $signup_info_cache_agent->{"ship_$_"} = $cust_main->get("$prefix$_")
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   #shares some stuff with htdocs/edit/process/cust_main.cgi... take any
513   # common that are still here and library them.
514   my $template_custnum = $conf->config('signup_server-prepaid-template-custnum');
515   my $cust_main;
516   if ( $template_custnum && $packet->{prepaid_shortform} ) {
517
518     my $template_cust = qsearchs('cust_main', { 'custnum' => $template_custnum } );
519     return { 'error' => 'Configuration error' } unless $template_cust;
520     $cust_main = new FS::cust_main ( {
521       'agentnum'      => $agentnum,
522       'refnum'        => $packet->{refnum}
523                          || $conf->config('signup_server-default_refnum'),
524
525       ( map { $_ => $template_cust->$_ } qw( 
526               last first company address1 address2 
527               city county state zip country
528               daytime night fax 
529
530               ship_last ship_first ship_company ship_address1 ship_address2
531               ship_city ship_county ship_state ship_zip ship_country
532               ship_daytime ship_night ship_fax
533             )
534       ),
535
536       ( map { $_ => $packet->{$_} } qw(
537               ss stateid stateid_state
538
539               payby
540               payinfo paycvv paydate payname paystate paytype
541               paystart_month paystart_year payissue
542               payip
543
544               referral_custnum comments
545             )
546       ),
547
548     } );
549
550   } else {
551
552     $cust_main = new FS::cust_main ( {
553       #'custnum'          => '',
554       'agentnum'      => $agentnum,
555       'refnum'        => $packet->{refnum}
556                          || $conf->config('signup_server-default_refnum'),
557
558       map { $_ => $packet->{$_} } qw(
559
560         last first ss company address1 address2
561         city county state zip country
562         daytime night fax stateid stateid_state
563
564         ship_last ship_first ship_ss ship_company ship_address1 ship_address2
565         ship_city ship_county ship_state ship_zip ship_country
566         ship_daytime ship_night ship_fax
567
568         payby
569         payinfo paycvv paydate payname paystate paytype
570         paystart_month paystart_year payissue
571         payip
572         override_ban_warn
573
574         referral_custnum comments
575       )
576
577     } );
578   }
579
580   my $agent = qsearchs('agent', { 'agentnum' => $agentnum } );
581   if ( $conf->exists('agent-ship_address', $agentnum) 
582     && $agent->agent_custnum ) {
583
584     my $agent_cust_main = $agent->agent_cust_main;
585     my $prefix = length($agent_cust_main->ship_last) ? 'ship_' : '';
586     $cust_main->set("ship_$_", $agent_cust_main->get("$prefix$_") )
587       foreach qw( address1 city county state zip country );
588
589     $cust_main->set("ship_$_", $cust_main->get($_))
590       foreach qw( last first );
591
592   }
593
594
595   return { 'error' => "Illegal payment type" }
596     unless grep { $_ eq $packet->{'payby'} }
597                 $conf->config('signup_server-payby');
598
599   if (FS::payby->realtime($packet->{payby})
600     and not $conf->exists('signup_server-third_party_as_card')) {
601     my $payby = $packet->{payby};
602
603     my $agent = qsearchs('agent', { 'agentnum' => $agentnum });
604     return { 'error' => "Unknown reseller" }
605       unless $agent;
606
607     my $gw;
608     my $gatewaynum = $conf->config('selfservice-payment_gateway');
609     if ( $gatewaynum ) {
610       $gw = qsearchs('payment_gateway', { gatewaynum => $gatewaynum });
611       die "configured gatewaynum $gatewaynum not found!" if !$gw;
612     }
613     else {
614       $gw = $agent->payment_gateway( 'method'  => FS::payby->payby2bop($payby),
615                                      'nofatal' => 1,
616                                     );
617     }
618
619     $cust_main->payby('BILL')   # MCRD better?
620       if $gw && $gw->gateway_namespace eq 'Business::OnlineThirdPartyPayment';
621   }
622
623   $cust_main->payinfo($cust_main->daytime)
624     if $cust_main->payby eq 'LECB' && ! $cust_main->payinfo;
625
626   my @invoicing_list = $packet->{'invoicing_list'}
627                          ? split( /\s*\,\s*/, $packet->{'invoicing_list'} )
628                          : ();
629
630   $packet->{'pkgpart'} =~ /^(\d+)$/ or '' =~ /^()$/;
631   my $pkgpart = $1;
632   return { 'error' => 'Please select a package' } unless $pkgpart; #msgcat
633
634   my $part_pkg =
635     qsearchs( 'part_pkg', { 'pkgpart' => $pkgpart } )
636       or return { 'error' => "WARNING: unknown pkgpart: $pkgpart" };
637   my $svcpart = $part_pkg->svcpart($svc_x);
638
639   my $reg_code = '';
640   if ( $packet->{'reg_code'} ) {
641     $reg_code = qsearchs( 'reg_code', { 'code'     => $packet->{'reg_code'},
642                                         'agentnum' => $agentnum,             } )
643       or return { 'error' => 'Unknown registration code' };
644   }
645
646   my $cust_pkg = new FS::cust_pkg ( {
647     #later#'custnum' => $custnum,
648     'pkgpart'    => $packet->{'pkgpart'},
649     'promo_code' => $packet->{'promo_code'},
650     'reg_code'   => $packet->{'reg_code'},
651   } );
652   #my $error = $cust_pkg->check;
653   #return { 'error' => $error } if $error;
654
655   #should be all auto-magic and shit
656   my @svc = ();
657   if ( $svc_x eq 'svc_acct' ) {
658
659     my $svc = new FS::svc_acct {
660       'svcpart'   => $svcpart,
661       map { $_ => $packet->{$_} }
662         qw( username _password sec_phrase popnum ),
663     };
664
665     my @acct_snarf;
666     my $snarfnum = 1;
667     while (    exists($packet->{"snarf_machine$snarfnum"})
668             && length($packet->{"snarf_machine$snarfnum"}) ) {
669       my $acct_snarf = new FS::acct_snarf ( {
670         'machine'   => $packet->{"snarf_machine$snarfnum"},
671         'protocol'  => $packet->{"snarf_protocol$snarfnum"},
672         'username'  => $packet->{"snarf_username$snarfnum"},
673         '_password' => $packet->{"snarf_password$snarfnum"},
674       } );
675       $snarfnum++;
676       push @acct_snarf, $acct_snarf;
677     }
678     $svc->child_objects( \@acct_snarf );
679     push @svc, $svc;
680
681   } elsif ( $svc_x eq 'svc_phone' ) {
682
683     push @svc, new FS::svc_phone ( {
684       'svcpart' => $svcpart,
685        map { $_ => $packet->{$_} }
686          qw( countrycode phonenum sip_password pin ),
687     } );
688
689   } elsif ( $svc_x eq 'svc_pbx' ) {
690
691     push @svc, new FS::svc_pbx ( {
692         'svcpart' => $svcpart,
693         map { $_ => $packet->{$_} } 
694           qw( id title ),
695         } );
696   
697   } else {
698     die "unknown signup service $svc_x";
699   }
700
701   if ($packet->{'mac_addr'} && $conf->exists('signup_server-mac_addr_svcparts'))
702   {
703
704     my %mac_addr_svcparts = map { $_ => 1 }
705                             $conf->config('signup_server-mac_addr_svcparts');
706     my @pkg_svc = grep { $_->quantity && $mac_addr_svcparts{$_->svcpart} }
707                   $cust_pkg->part_pkg->pkg_svc;
708
709     return { 'error' => 'No service defined to assign mac address' }
710       unless @pkg_svc;
711
712     my $svc = new FS::svc_acct {
713       'svcpart'   => $pkg_svc[0]->svcpart, #multiple matches? alas..
714       'username'  => $packet->{'mac_addr'},
715       '_password' => '', #blank as requested (set passwordmin to 0)
716     };
717
718     push @svc, $svc;
719
720   }
721
722   foreach my $svc ( @svc ) {
723     my $y = $svc->setdefault; # arguably should be in new method
724     return { 'error' => $y } if $y && !ref($y);
725     #$error = $svc->check;
726     #return { 'error' => $error } if $error;
727   }
728
729   #setup a job dependancy to delay provisioning
730   my $placeholder = new FS::queue ( {
731     'job'    => 'FS::ClientAPI::Signup::__placeholder',
732     'status' => 'locked',
733   } );
734   my $error = $placeholder->insert;
735   return { 'error' => $error } if $error;
736
737   use Tie::RefHash;
738   tie my %hash, 'Tie::RefHash';
739   %hash = ( $cust_pkg => \@svc );
740   #msgcat
741   $error = $cust_main->insert(
742     \%hash,
743     \@invoicing_list,
744     'depend_jobnum' => $placeholder->jobnum,
745   );
746   if ( $error ) {
747     my $perror = $placeholder->delete;
748     $error .= " (Additionally, error removing placeholder: $perror)" if $perror;
749     return { 'error' => $error };
750   }
751
752   if ( $conf->exists('signup_server-realtime') ) {
753
754     #warn "$me Billing customer...\n" if $Debug;
755
756     my $bill_error = $cust_main->bill( 'depend_jobnum'=>$placeholder->jobnum );
757     #warn "$me error billing new customer: $bill_error"
758     #  if $bill_error;
759
760     $bill_error = $cust_main->apply_payments_and_credits;
761     #warn "$me error applying payments and credits for".
762     #     " new customer: $bill_error"
763     #  if $bill_error;
764
765     $bill_error = $cust_main->realtime_collect(
766        method        => FS::payby->payby2bop( $packet->{payby} ),
767        depend_jobnum => $placeholder->jobnum,
768        selfservice   => 1,
769     );
770     #warn "$me error collecting from new customer: $bill_error"
771     #  if $bill_error;
772
773     if ($bill_error && ref($bill_error) eq 'HASH') {
774       return { 'error' => '_collect',
775                ( map { $_ => $bill_error->{$_} }
776                  qw(popup_url reference collectitems)
777                ),
778                amount => $cust_main->balance,
779              };
780     }
781
782     $bill_error = $cust_main->apply_payments_and_credits;
783     #warn "$me error applying payments and credits for".
784     #     " new customer: $bill_error"
785     #  if $bill_error;
786
787     if ( $cust_main->balance > 0 ) {
788
789       #this makes sense.  credit is "un-doing" the invoice
790       $cust_main->credit( $cust_main->balance, 'signup server decline',
791                           'reason_type' => $conf->config('signup_credit_type'),
792                         );
793       $cust_main->apply_credits;
794
795       #should check list for errors...
796       #$cust_main->suspend;
797       local $FS::svc_Common::noexport_hack = 1;
798       $cust_main->cancel('quiet'=>1);
799
800       my $perror = $placeholder->depended_delete;
801       warn "error removing provisioning jobs after decline: $perror" if $perror;
802       unless ( $perror ) {
803         $perror = $placeholder->delete;
804         warn "error removing placeholder after decline: $perror" if $perror;
805       }
806
807       return { 'error' => '_decline' };
808     }
809
810   }
811
812   if ( $reg_code ) {
813     $error = $reg_code->delete;
814     return { 'error' => $error } if $error;
815   }
816
817   $error = $placeholder->delete;
818   return { 'error' => $error } if $error;
819
820   if ( $conf->exists('signup-duplicate_cc-warn_hours') ) {
821     my $hours = $conf->config('signup-duplicate_cc-warn_hours');
822     my $ban = new FS::banned_pay $cust_main->_new_banned_pay_hashref;
823     $ban->end_date( int( time + $hours*3600 ) );
824     $ban->bantype('warn');
825     $ban->reason('signup-duplicate_cc-warn_hours');
826     $error = $ban->insert;
827     warn "WARNING: error inserting temporary banned_pay for ".
828          " signup-duplicate_cc-warn_hours (proceeding anyway): $error"
829       if $error;
830   }
831
832   my %return = ( 'error'          => '',
833                  'signup_service' => $svc_x,
834                  'custnum'        => $cust_main->custnum,
835                );
836
837   if ( $svc[0] ) {
838
839     $return{'svcnum'} = $svc[0]->svcnum;
840
841     if ( $svc_x eq 'svc_acct' ) {
842       $return{$_} = $svc[0]->$_() for qw( username _password );
843     } elsif ( $svc_x eq 'svc_phone' ) {
844       $return{$_} = $svc[0]->$_() for qw(countrycode phonenum sip_password pin);
845     } elsif ( $svc_x eq 'svc_pbx' ) {
846       #$return{$_} = $svc[0]->$_() for qw( ) #nothing yet
847      } else {
848       return {'error' => "configuration error: unknown signup service $svc_x"};
849       #die "unknown signup service $svc_x";
850       # return an error that's visible to someone somewhere
851     }
852
853   }
854
855   return \%return;
856
857 }
858
859 sub capture_payment {
860   my $packet = shift;
861
862   warn "$me capture_payment called on $packet\n" if $DEBUG;
863
864   ###
865   # identify processor/gateway from called back URL
866   ###
867
868   my $conf = new FS::Conf;
869
870   my $payment_gateway;
871   if ( my $gwnum = $conf->config('selfservice-payment_gateway') ) {
872     $payment_gateway = qsearchs('payment_gateway', { 'gatewaynum' => $gwnum })
873       or die "configured gatewaynum $gwnum not found!";
874   }
875   else {
876     my $url = $packet->{url};
877
878     $payment_gateway = qsearchs('payment_gateway', 
879         { 'gateway_callback_url' => popurl(0, $url) } 
880       );
881     if (!$payment_gateway) { 
882
883       my ( $processor, $login, $password, $action, @bop_options ) =
884         $conf->config('business-onlinepayment');
885       $action ||= 'normal authorization';
886       pop @bop_options if scalar(@bop_options) % 2 && $bop_options[-1] =~ /^\s*$/;
887       die "No real-time processor is enabled - ".
888           "did you set the business-onlinepayment configuration value?\n"
889         unless $processor;
890
891       $payment_gateway = new FS::payment_gateway( {
892         gateway_namespace => $conf->config('business-onlinepayment-namespace'),
893         gateway_module    => $processor,
894         gateway_username  => $login,
895         gateway_password  => $password,
896         gateway_action    => $action,
897         options   => [ ( @bop_options ) ],
898       });
899     }
900   }
901  
902   die "No real-time third party processor is enabled - ".
903       "did you set the business-onlinepayment configuration value?\n*"
904     unless $payment_gateway->gateway_namespace eq 'Business::OnlineThirdPartyPayment';
905
906   ###
907   # locate pending transaction
908   ###
909
910   eval "use Business::OnlineThirdPartyPayment";
911   die $@ if $@;
912
913   my $transaction =
914     new Business::OnlineThirdPartyPayment( $payment_gateway->gateway_module,
915                                            @{ [ $payment_gateway->options ] },
916                                          );
917
918   my $paypendingnum = $transaction->reference($packet->{data});
919
920   my $cust_pay_pending =
921     qsearchs('cust_pay_pending', { paypendingnum => $paypendingnum } );
922
923   unless ($cust_pay_pending) {
924     my $bill_error = "No payment is being processed with id $paypendingnum".
925                      "; Transaction aborted.";
926     return { error => '_decline', bill_error => $bill_error };
927   }
928
929   if ($cust_pay_pending->status ne 'thirdparty') {
930     my $bill_error = "Payment with id $paypendingnum is not thirdparty, but ".
931                      $cust_pay_pending->status.  "; Transaction aborted.";
932     return { error => '_decline', bill_error => $bill_error };
933   }
934
935   my $cust_main = $cust_pay_pending->cust_main;
936   my $bill_error =
937     $cust_main->realtime_botpp_capture( $cust_pay_pending, 
938       %{$packet->{data}},
939       apply => 1,
940   );
941
942   return { 'error'      => ( $bill_error->{bill_error} ? '_decline' : '' ),
943            %$bill_error,
944          };
945
946 }
947
948 1;