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