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