more per-agent options, #15973
[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       'agent_ship_address' => scalar($conf->exists('agent-ship_address')),
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       or return { 'error' => "Self-service agent #$agentnum does not exist" };
322     warn "$me has agent $agent\n" if $DEBUG > 1;
323     my @paybys = @{ $signup_info->{'payby'} };
324     $signup_info->{'hide_payment_fields'} = [];
325
326     my $gatewaynum = $conf->config('selfservice-payment_gateway');
327     my $force_gateway;
328     if ( $gatewaynum ) {
329       $force_gateway = qsearchs('payment_gateway', { gatewaynum => $gatewaynum });
330       warn "using forced gateway #$gatewaynum - " .
331         $force_gateway->gateway_username . '@' . $force_gateway->gateway_module
332         if $DEBUG > 1;
333       die "configured gatewaynum $gatewaynum not found!" if !$force_gateway;
334     }
335     foreach my $payby (@paybys) {
336       warn "$me checking $payby payment fields\n" if $DEBUG > 1;
337       my $hide = 0;
338       if ( FS::payby->realtime($payby) ) {
339         my $gateway = $force_gateway || 
340           $agent->payment_gateway( 'method'  => FS::payby->payby2bop($payby),
341                                    'nofatal' => 1,
342                                  );
343         if ( $gateway && $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     warn "$me done setting agent-specific payment flag\n" if $DEBUG > 1;
353
354     warn "$me setting agent-specific package list\n" if $DEBUG > 1;
355     $signup_info->{'part_pkg'} = $signup_info->{'agentnum2part_pkg'}{$agentnum}
356       unless @{ $signup_info->{'part_pkg'} };
357     warn "$me done setting agent-specific package list\n" if $DEBUG > 1;
358
359     warn "$me setting agent-specific adv. source list\n" if $DEBUG > 1;
360     $signup_info->{'part_referral'} =
361       [
362         map { $_->hashref }
363           qsearch( {
364                      'table'     => 'part_referral',
365                      'hashref'   => { 'disabled' => '' },
366                      'extra_sql' => "AND (    agentnum = $agentnum  ".
367                                     "      OR agentnum IS NULL    ) ",
368                    },
369                  )
370       ];
371     warn "$me done setting agent-specific adv. source list\n" if $DEBUG > 1;
372
373     $signup_info->{'agent_name'} = $agent->agent;
374
375     $signup_info->{'company_name'} = $conf->config('company_name', $agentnum);
376
377     if ( $signup_info->{'agent_ship_address'} && $agent->agent_custnum ) {
378       my $cust_main = $agent->agent_cust_main;
379       my $prefix = length($cust_main->ship_last) ? 'ship_' : '';
380       $signup_info->{"ship_$_"} = $cust_main->get("$prefix$_")
381         foreach qw( address1 city county state zip country );
382     }
383
384     #some of the above could probably be cached, too
385
386     my $signup_info_cache_agent = $cache->get("signup_info_cache_agent$agentnum");
387
388     if ( $signup_info_cache_agent ) {
389
390       warn "$me loading cached signup info for agentnum $agentnum\n"
391         if $DEBUG > 1;
392
393     } else {
394
395       warn "$me populating signup info cache for agentnum $agentnum\n"
396         if $DEBUG > 1;
397
398       $signup_info_cache_agent = {
399         #( map { $_ => scalar( $conf->config($_, $agentnum) ) }
400         #  qw( company_name ) ),
401         ( map { $_ => scalar( $conf->config("selfservice-$_", $agentnum ) ) }
402           qw( body_bgcolor box_bgcolor menu_bgcolor ) ),
403         ( map { $_ => join("\n", $conf->config("selfservice-$_", $agentnum ) ) }
404           qw( head body_header body_footer ) ),
405         ( map { $_ => join("\n", $conf->config("signup_server-$_", $agentnum ) ) }
406           qw( terms_of_service ) ),
407
408         ( map { $_ => scalar($conf->exists($_, $agentnum)) } 
409           qw(cust_main-require_phone) ),
410       };
411
412       $cache->set("signup_info_cache_agent$agentnum", $signup_info_cache_agent);
413
414     }
415
416     $signup_info->{$_} = $signup_info_cache_agent->{$_}
417       foreach keys %$signup_info_cache_agent;
418
419   }
420   # else {
421   # delete $signup_info->{'part_pkg'};
422   #}
423
424   warn "$me sorting package list\n" if $DEBUG > 1;
425   $signup_info->{'part_pkg'} = [ sort { $a->{pkg} cmp $b->{pkg} }  # case?
426                                       @{ $signup_info->{'part_pkg'} }
427                                ];
428   warn "$me done sorting package list\n" if $DEBUG > 1;
429
430   if ( exists $packet->{'session_id'} ) {
431     my $agent_signup_info = { %$signup_info };
432     delete $agent_signup_info->{agentnum2part_pkg};
433     $agent_signup_info->{'agent'} = $session->{'agent'};
434     return $agent_signup_info;
435   } 
436   elsif ( exists $packet->{'keys'} ) {
437     my @keys = @{ $packet->{'keys'} };
438     return { map { $_ => $signup_info->{$_} } @keys };
439   }
440   else {
441     return $signup_info;
442   }
443
444 }
445
446 sub domain_select_hash {
447   my $packet = shift;
448
449   my $response = {};
450
451   if ($packet->{pkgpart}) {
452     my $part_pkg = qsearchs('part_pkg' => { 'pkgpart' => $packet->{pkgpart} } );
453     #$packet->{svcpart} = $part_pkg->svcpart('svc_acct')
454     $packet->{svcpart} = $part_pkg->svcpart
455       if $part_pkg;
456   }
457
458   if ($packet->{svcpart}) {
459     my $part_svc = qsearchs('part_svc' => { 'svcpart' => $packet->{svcpart} } );
460     $response->{'domsvc'} = $part_svc->part_svc_column('domsvc')->columnvalue
461       if ($part_svc && $part_svc->part_svc_column('domsvc')->columnflag  eq 'D');
462   }
463
464   $response->{'domains'}
465     = { domain_select_hash FS::svc_acct( map { $_ => $packet->{$_} }
466                                                  qw(svcpart pkgnum)
467                                        ) };
468
469   $response;
470 }
471
472 sub new_customer {
473   my $packet = shift;
474
475   my $conf = new FS::Conf;
476   my $svc_x = $conf->config('signup_server-service') || 'svc_acct';
477
478   if ( $svc_x eq 'svc_acct' ) {
479   
480     #things that aren't necessary in base class, but are for signup server
481       #return "Passwords don't match"
482       #  if $hashref->{'_password'} ne $hashref->{'_password2'}
483     return { 'error' => gettext('empty_password') }
484       unless length($packet->{'_password'});
485     # a bit inefficient for large numbers of pops
486     return { 'error' => gettext('no_access_number_selected') }
487       unless $packet->{'popnum'} || !scalar(qsearch('svc_acct_pop',{} ));
488
489   }
490   elsif ( $svc_x eq 'svc_pbx' ) {
491     #possibly some validation will be needed
492   }
493
494   my $agentnum;
495   if ( exists $packet->{'session_id'} ) {
496     my $cache = new FS::ClientAPI_SessionCache( {
497       'namespace' => 'FS::ClientAPI::Agent',
498     } );
499     my $session = $cache->get($packet->{'session_id'});
500     if ( $session ) {
501       $agentnum = $session->{'agentnum'};
502     } else {
503       return { 'error' => "Can't resume session" }; #better error message
504     }
505   } else {
506     $agentnum = $packet->{agentnum}
507                 || $conf->config('signup_server-default_agentnum');
508   }
509
510   #shares some stuff with htdocs/edit/process/cust_main.cgi... take any
511   # common that are still here and library them.
512   my $template_custnum = $conf->config('signup_server-prepaid-template-custnum');
513   my $cust_main;
514   if ( $template_custnum && $packet->{prepaid_shortform} ) {
515
516     my $template_cust = qsearchs('cust_main', { 'custnum' => $template_custnum } );
517     return { 'error' => 'Configuration error' } unless $template_cust;
518     $cust_main = new FS::cust_main ( {
519       'agentnum'      => $agentnum,
520       'refnum'        => $packet->{refnum}
521                          || $conf->config('signup_server-default_refnum'),
522
523       ( map { $_ => $template_cust->$_ } qw( 
524               last first company address1 address2 
525               city county state zip country
526               daytime night fax 
527
528               ship_last ship_first ship_company ship_address1 ship_address2
529               ship_city ship_county ship_state ship_zip ship_country
530               ship_daytime ship_night ship_fax
531             )
532       ),
533
534       ( map { $_ => $packet->{$_} } qw(
535               ss stateid stateid_state
536
537               payby
538               payinfo paycvv paydate payname paystate paytype
539               paystart_month paystart_year payissue
540               payip
541
542               referral_custnum comments
543             )
544       ),
545
546     } );
547
548   } else {
549
550     $cust_main = new FS::cust_main ( {
551       #'custnum'          => '',
552       'agentnum'      => $agentnum,
553       'refnum'        => $packet->{refnum}
554                          || $conf->config('signup_server-default_refnum'),
555
556       map { $_ => $packet->{$_} } qw(
557
558         last first ss company address1 address2
559         city county state zip country
560         daytime night fax stateid stateid_state
561
562         ship_last ship_first ship_ss ship_company ship_address1 ship_address2
563         ship_city ship_county ship_state ship_zip ship_country
564         ship_daytime ship_night ship_fax
565
566         payby
567         payinfo paycvv paydate payname paystate paytype
568         paystart_month paystart_year payissue
569         payip
570         override_ban_warn
571
572         referral_custnum comments
573       )
574
575     } );
576   }
577
578   my $agent = qsearchs('agent', { 'agentnum' => $agentnum } );
579   if ( $conf->exists('agent_ship_address') && $agent->agent_custnum ) {
580     my $agent_cust_main = $agent->agent_cust_main;
581     my $prefix = length($agent_cust_main->ship_last) ? 'ship_' : '';
582     $cust_main->set("ship_$_", $agent_cust_main->get("$prefix$_") )
583       foreach qw( address1 city county state zip country );
584
585     $cust_main->set("ship_$_", $cust_main->get($_))
586       foreach qw( last first );
587
588   }
589
590
591   return { 'error' => "Illegal payment type" }
592     unless grep { $_ eq $packet->{'payby'} }
593                 $conf->config('signup_server-payby');
594
595   if (FS::payby->realtime($packet->{payby})
596     and not $conf->exists('signup_server-third_party_as_card')) {
597     my $payby = $packet->{payby};
598
599     my $agent = qsearchs('agent', { 'agentnum' => $agentnum });
600     return { 'error' => "Unknown reseller" }
601       unless $agent;
602
603     my $gw;
604     my $gatewaynum = $conf->config('selfservice-payment_gateway');
605     if ( $gatewaynum ) {
606       $gw = qsearchs('payment_gateway', { gatewaynum => $gatewaynum });
607       die "configured gatewaynum $gatewaynum not found!" if !$gw;
608     }
609     else {
610       $gw = $agent->payment_gateway( 'method'  => FS::payby->payby2bop($payby),
611                                      'nofatal' => 1,
612                                     );
613     }
614
615     $cust_main->payby('BILL')   # MCRD better?
616       if $gw && $gw->gateway_namespace eq 'Business::OnlineThirdPartyPayment';
617   }
618
619   $cust_main->payinfo($cust_main->daytime)
620     if $cust_main->payby eq 'LECB' && ! $cust_main->payinfo;
621
622   my @invoicing_list = $packet->{'invoicing_list'}
623                          ? split( /\s*\,\s*/, $packet->{'invoicing_list'} )
624                          : ();
625
626   $packet->{'pkgpart'} =~ /^(\d+)$/ or '' =~ /^()$/;
627   my $pkgpart = $1;
628   return { 'error' => 'Please select a package' } unless $pkgpart; #msgcat
629
630   my $part_pkg =
631     qsearchs( 'part_pkg', { 'pkgpart' => $pkgpart } )
632       or return { 'error' => "WARNING: unknown pkgpart: $pkgpart" };
633   my $svcpart = $part_pkg->svcpart($svc_x);
634
635   my $reg_code = '';
636   if ( $packet->{'reg_code'} ) {
637     $reg_code = qsearchs( 'reg_code', { 'code'     => $packet->{'reg_code'},
638                                         'agentnum' => $agentnum,             } )
639       or return { 'error' => 'Unknown registration code' };
640   }
641
642   my $cust_pkg = new FS::cust_pkg ( {
643     #later#'custnum' => $custnum,
644     'pkgpart'    => $packet->{'pkgpart'},
645     'promo_code' => $packet->{'promo_code'},
646     'reg_code'   => $packet->{'reg_code'},
647   } );
648   #my $error = $cust_pkg->check;
649   #return { 'error' => $error } if $error;
650
651   #should be all auto-magic and shit
652   my @svc = ();
653   if ( $svc_x eq 'svc_acct' ) {
654
655     my $svc = new FS::svc_acct {
656       'svcpart'   => $svcpart,
657       map { $_ => $packet->{$_} }
658         qw( username _password sec_phrase popnum ),
659     };
660
661     my @acct_snarf;
662     my $snarfnum = 1;
663     while (    exists($packet->{"snarf_machine$snarfnum"})
664             && length($packet->{"snarf_machine$snarfnum"}) ) {
665       my $acct_snarf = new FS::acct_snarf ( {
666         'machine'   => $packet->{"snarf_machine$snarfnum"},
667         'protocol'  => $packet->{"snarf_protocol$snarfnum"},
668         'username'  => $packet->{"snarf_username$snarfnum"},
669         '_password' => $packet->{"snarf_password$snarfnum"},
670       } );
671       $snarfnum++;
672       push @acct_snarf, $acct_snarf;
673     }
674     $svc->child_objects( \@acct_snarf );
675     push @svc, $svc;
676
677   } elsif ( $svc_x eq 'svc_phone' ) {
678
679     push @svc, new FS::svc_phone ( {
680       'svcpart' => $svcpart,
681        map { $_ => $packet->{$_} }
682          qw( countrycode phonenum sip_password pin ),
683     } );
684
685   } elsif ( $svc_x eq 'svc_pbx' ) {
686
687     push @svc, new FS::svc_pbx ( {
688         'svcpart' => $svcpart,
689         map { $_ => $packet->{$_} } 
690           qw( id title ),
691         } );
692   
693   } else {
694     die "unknown signup service $svc_x";
695   }
696
697   if ($packet->{'mac_addr'} && $conf->exists('signup_server-mac_addr_svcparts'))
698   {
699
700     my %mac_addr_svcparts = map { $_ => 1 }
701                             $conf->config('signup_server-mac_addr_svcparts');
702     my @pkg_svc = grep { $_->quantity && $mac_addr_svcparts{$_->svcpart} }
703                   $cust_pkg->part_pkg->pkg_svc;
704
705     return { 'error' => 'No service defined to assign mac address' }
706       unless @pkg_svc;
707
708     my $svc = new FS::svc_acct {
709       'svcpart'   => $pkg_svc[0]->svcpart, #multiple matches? alas..
710       'username'  => $packet->{'mac_addr'},
711       '_password' => '', #blank as requested (set passwordmin to 0)
712     };
713
714     push @svc, $svc;
715
716   }
717
718   foreach my $svc ( @svc ) {
719     my $y = $svc->setdefault; # arguably should be in new method
720     return { 'error' => $y } if $y && !ref($y);
721     #$error = $svc->check;
722     #return { 'error' => $error } if $error;
723   }
724
725   #setup a job dependancy to delay provisioning
726   my $placeholder = new FS::queue ( {
727     'job'    => 'FS::ClientAPI::Signup::__placeholder',
728     'status' => 'locked',
729   } );
730   my $error = $placeholder->insert;
731   return { 'error' => $error } if $error;
732
733   use Tie::RefHash;
734   tie my %hash, 'Tie::RefHash';
735   %hash = ( $cust_pkg => \@svc );
736   #msgcat
737   $error = $cust_main->insert(
738     \%hash,
739     \@invoicing_list,
740     'depend_jobnum' => $placeholder->jobnum,
741   );
742   if ( $error ) {
743     my $perror = $placeholder->delete;
744     $error .= " (Additionally, error removing placeholder: $perror)" if $perror;
745     return { 'error' => $error };
746   }
747
748   if ( $conf->exists('signup_server-realtime') ) {
749
750     #warn "$me Billing customer...\n" if $Debug;
751
752     my $bill_error = $cust_main->bill( 'depend_jobnum'=>$placeholder->jobnum );
753     #warn "$me error billing new customer: $bill_error"
754     #  if $bill_error;
755
756     $bill_error = $cust_main->apply_payments_and_credits;
757     #warn "$me error applying payments and credits for".
758     #     " new customer: $bill_error"
759     #  if $bill_error;
760
761     $bill_error = $cust_main->realtime_collect(
762        method        => FS::payby->payby2bop( $packet->{payby} ),
763        depend_jobnum => $placeholder->jobnum,
764        selfservice   => 1,
765     );
766     #warn "$me error collecting from new customer: $bill_error"
767     #  if $bill_error;
768
769     if ($bill_error && ref($bill_error) eq 'HASH') {
770       return { 'error' => '_collect',
771                ( map { $_ => $bill_error->{$_} }
772                  qw(popup_url reference collectitems)
773                ),
774                amount => $cust_main->balance,
775              };
776     }
777
778     $bill_error = $cust_main->apply_payments_and_credits;
779     #warn "$me error applying payments and credits for".
780     #     " new customer: $bill_error"
781     #  if $bill_error;
782
783     if ( $cust_main->balance > 0 ) {
784
785       #this makes sense.  credit is "un-doing" the invoice
786       $cust_main->credit( $cust_main->balance, 'signup server decline',
787                           'reason_type' => $conf->config('signup_credit_type'),
788                         );
789       $cust_main->apply_credits;
790
791       #should check list for errors...
792       #$cust_main->suspend;
793       local $FS::svc_Common::noexport_hack = 1;
794       $cust_main->cancel('quiet'=>1);
795
796       my $perror = $placeholder->depended_delete;
797       warn "error removing provisioning jobs after decline: $perror" if $perror;
798       unless ( $perror ) {
799         $perror = $placeholder->delete;
800         warn "error removing placeholder after decline: $perror" if $perror;
801       }
802
803       return { 'error' => '_decline' };
804     }
805
806   }
807
808   if ( $reg_code ) {
809     $error = $reg_code->delete;
810     return { 'error' => $error } if $error;
811   }
812
813   $error = $placeholder->delete;
814   return { 'error' => $error } if $error;
815
816   if ( $conf->exists('signup-duplicate_cc-warn_hours') ) {
817     my $hours = $conf->config('signup-duplicate_cc-warn_hours');
818     my $ban = new FS::banned_pay $cust_main->_new_banned_pay_hashref;
819     $ban->end_date( int( time + $hours*3600 ) );
820     $ban->bantype('warn');
821     $ban->reason('signup-duplicate_cc-warn_hours');
822     $error = $ban->insert;
823     warn "WARNING: error inserting temporary banned_pay for ".
824          " signup-duplicate_cc-warn_hours (proceeding anyway): $error"
825       if $error;
826   }
827
828   my %return = ( 'error'          => '',
829                  'signup_service' => $svc_x,
830                  'custnum'        => $cust_main->custnum,
831                );
832
833   if ( $svc[0] ) {
834
835     $return{'svcnum'} = $svc[0]->svcnum;
836
837     if ( $svc_x eq 'svc_acct' ) {
838       $return{$_} = $svc[0]->$_() for qw( username _password );
839     } elsif ( $svc_x eq 'svc_phone' ) {
840       $return{$_} = $svc[0]->$_() for qw(countrycode phonenum sip_password pin);
841     } elsif ( $svc_x eq 'svc_pbx' ) {
842       #$return{$_} = $svc[0]->$_() for qw( ) #nothing yet
843      } else {
844       return {'error' => "configuration error: unknown signup service $svc_x"};
845       #die "unknown signup service $svc_x";
846       # return an error that's visible to someone somewhere
847     }
848
849   }
850
851   return \%return;
852
853 }
854
855 sub capture_payment {
856   my $packet = shift;
857
858   warn "$me capture_payment called on $packet\n" if $DEBUG;
859
860   ###
861   # identify processor/gateway from called back URL
862   ###
863
864   my $conf = new FS::Conf;
865
866   my $payment_gateway;
867   if ( my $gwnum = $conf->config('selfservice-payment_gateway') ) {
868     $payment_gateway = qsearchs('payment_gateway', { 'gatewaynum' => $gwnum })
869       or die "configured gatewaynum $gwnum not found!";
870   }
871   else {
872     my $url = $packet->{url};
873
874     $payment_gateway = qsearchs('payment_gateway', 
875         { 'gateway_callback_url' => popurl(0, $url) } 
876       );
877     if (!$payment_gateway) { 
878
879       my ( $processor, $login, $password, $action, @bop_options ) =
880         $conf->config('business-onlinepayment');
881       $action ||= 'normal authorization';
882       pop @bop_options if scalar(@bop_options) % 2 && $bop_options[-1] =~ /^\s*$/;
883       die "No real-time processor is enabled - ".
884           "did you set the business-onlinepayment configuration value?\n"
885         unless $processor;
886
887       $payment_gateway = new FS::payment_gateway( {
888         gateway_namespace => $conf->config('business-onlinepayment-namespace'),
889         gateway_module    => $processor,
890         gateway_username  => $login,
891         gateway_password  => $password,
892         gateway_action    => $action,
893         options   => [ ( @bop_options ) ],
894       });
895     }
896   }
897  
898   die "No real-time third party processor is enabled - ".
899       "did you set the business-onlinepayment configuration value?\n*"
900     unless $payment_gateway->gateway_namespace eq 'Business::OnlineThirdPartyPayment';
901
902   ###
903   # locate pending transaction
904   ###
905
906   eval "use Business::OnlineThirdPartyPayment";
907   die $@ if $@;
908
909   my $transaction =
910     new Business::OnlineThirdPartyPayment( $payment_gateway->gateway_module,
911                                            @{ [ $payment_gateway->options ] },
912                                          );
913
914   my $paypendingnum = $transaction->reference($packet->{data});
915
916   my $cust_pay_pending =
917     qsearchs('cust_pay_pending', { paypendingnum => $paypendingnum } );
918
919   unless ($cust_pay_pending) {
920     my $bill_error = "No payment is being processed with id $paypendingnum".
921                      "; Transaction aborted.";
922     return { error => '_decline', bill_error => $bill_error };
923   }
924
925   if ($cust_pay_pending->status ne 'thirdparty') {
926     my $bill_error = "Payment with id $paypendingnum is not thirdparty, but ".
927                      $cust_pay_pending->status.  "; Transaction aborted.";
928     return { error => '_decline', bill_error => $bill_error };
929   }
930
931   my $cust_main = $cust_pay_pending->cust_main;
932   my $bill_error =
933     $cust_main->realtime_botpp_capture( $cust_pay_pending, 
934       %{$packet->{data}},
935       apply => 1,
936   );
937
938   return { 'error'      => ( $bill_error->{bill_error} ? '_decline' : '' ),
939            %$bill_error,
940          };
941
942 }
943
944 1;