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