assorted drupal self-service fixes, RT#9380
[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     return $agent_signup_info;
399   } 
400   elsif ( exists $packet->{'keys'} ) {
401     my @keys = @{ $packet->{'keys'} };
402     return { map { $_ => $signup_info->{$_} } @keys };
403   }
404   else {
405     return $signup_info;
406   }
407
408 }
409
410 sub domain_select_hash {
411   my $packet = shift;
412
413   my $response = {};
414
415   if ($packet->{pkgpart}) {
416     my $part_pkg = qsearchs('part_pkg' => { 'pkgpart' => $packet->{pkgpart} } );
417     #$packet->{svcpart} = $part_pkg->svcpart('svc_acct')
418     $packet->{svcpart} = $part_pkg->svcpart
419       if $part_pkg;
420   }
421
422   if ($packet->{svcpart}) {
423     my $part_svc = qsearchs('part_svc' => { 'svcpart' => $packet->{svcpart} } );
424     $response->{'domsvc'} = $part_svc->part_svc_column('domsvc')->columnvalue
425       if ($part_svc && $part_svc->part_svc_column('domsvc')->columnflag  eq 'D');
426   }
427
428   $response->{'domains'}
429     = { domain_select_hash FS::svc_acct( map { $_ => $packet->{$_} }
430                                                  qw(svcpart pkgnum)
431                                        ) };
432
433   $response;
434 }
435
436 sub new_customer {
437   my $packet = shift;
438
439   my $conf = new FS::Conf;
440   my $svc_x = $conf->config('signup_server-service') || 'svc_acct';
441
442   if ( $svc_x eq 'svc_acct' ) {
443   
444     #things that aren't necessary in base class, but are for signup server
445       #return "Passwords don't match"
446       #  if $hashref->{'_password'} ne $hashref->{'_password2'}
447     return { 'error' => gettext('empty_password') }
448       unless length($packet->{'_password'});
449     # a bit inefficient for large numbers of pops
450     return { 'error' => gettext('no_access_number_selected') }
451       unless $packet->{'popnum'} || !scalar(qsearch('svc_acct_pop',{} ));
452
453   }
454
455   my $agentnum;
456   if ( exists $packet->{'session_id'} ) {
457     my $cache = new FS::ClientAPI_SessionCache( {
458       'namespace' => 'FS::ClientAPI::Agent',
459     } );
460     my $session = $cache->get($packet->{'session_id'});
461     if ( $session ) {
462       $agentnum = $session->{'agentnum'};
463     } else {
464       return { 'error' => "Can't resume session" }; #better error message
465     }
466   } else {
467     $agentnum = $packet->{agentnum}
468                 || $conf->config('signup_server-default_agentnum');
469   }
470
471   #shares some stuff with htdocs/edit/process/cust_main.cgi... take any
472   # common that are still here and library them.
473   my $cust_main = new FS::cust_main ( {
474     #'custnum'          => '',
475     'agentnum'      => $agentnum,
476     'refnum'        => $packet->{refnum}
477                        || $conf->config('signup_server-default_refnum'),
478
479     map { $_ => $packet->{$_} } qw(
480
481       last first ss company address1 address2
482       city county state zip country
483       daytime night fax stateid stateid_state
484
485       ship_last ship_first ship_ss ship_company ship_address1 ship_address2
486       ship_city ship_county ship_state ship_zip ship_country
487       ship_daytime ship_night ship_fax
488
489       payby
490       payinfo paycvv paydate payname paystate paytype
491       paystart_month paystart_year payissue
492       payip
493
494       referral_custnum comments
495     )
496
497   } );
498
499   my $agent = qsearchs('agent', { 'agentnum' => $agentnum } );
500   if ( $conf->exists('agent_ship_address') && $agent->agent_custnum ) {
501     my $agent_cust_main = $agent->agent_cust_main;
502     my $prefix = length($agent_cust_main->ship_last) ? 'ship_' : '';
503     $cust_main->set("ship_$_", $agent_cust_main->get("$prefix$_") )
504       foreach qw( address1 city county state zip country );
505
506     $cust_main->set("ship_$_", $cust_main->get($_))
507       foreach qw( last first );
508
509   }
510
511
512   return { 'error' => "Illegal payment type" }
513     unless grep { $_ eq $packet->{'payby'} }
514                 $conf->config('signup_server-payby');
515
516   if (FS::payby->realtime($packet->{payby})) {
517     my $payby = $packet->{payby};
518
519     my $agent = qsearchs('agent', { 'agentnum' => $agentnum });
520     return { 'error' => "Unknown reseller" }
521       unless $agent;
522
523     my $gw = $agent->payment_gateway( 'method'  => FS::payby->payby2bop($payby),
524                                       'nofatal' => 1,
525                                     );
526
527     $cust_main->payby('BILL')   # MCRD better?
528       if $gw && $gw->gateway_namespace eq 'Business::OnlineThirdPartyPayment';
529   }
530
531   $cust_main->payinfo($cust_main->daytime)
532     if $cust_main->payby eq 'LECB' && ! $cust_main->payinfo;
533
534   my @invoicing_list = $packet->{'invoicing_list'}
535                          ? split( /\s*\,\s*/, $packet->{'invoicing_list'} )
536                          : ();
537
538   $packet->{'pkgpart'} =~ /^(\d+)$/ or '' =~ /^()$/;
539   my $pkgpart = $1;
540   return { 'error' => 'Please select a package' } unless $pkgpart; #msgcat
541
542   my $part_pkg =
543     qsearchs( 'part_pkg', { 'pkgpart' => $pkgpart } )
544       or return { 'error' => "WARNING: unknown pkgpart: $pkgpart" };
545   my $svcpart = $part_pkg->svcpart($svc_x);
546
547   my $reg_code = '';
548   if ( $packet->{'reg_code'} ) {
549     $reg_code = qsearchs( 'reg_code', { 'code'     => $packet->{'reg_code'},
550                                         'agentnum' => $agentnum,             } )
551       or return { 'error' => 'Unknown registration code' };
552   }
553
554   my $cust_pkg = new FS::cust_pkg ( {
555     #later#'custnum' => $custnum,
556     'pkgpart'    => $packet->{'pkgpart'},
557     'promo_code' => $packet->{'promo_code'},
558     'reg_code'   => $packet->{'reg_code'},
559   } );
560   #my $error = $cust_pkg->check;
561   #return { 'error' => $error } if $error;
562
563   #should be all auto-magic and shit
564   my @svc = ();
565   if ( $svc_x eq 'svc_acct' ) {
566
567     my $svc = new FS::svc_acct {
568       'svcpart'   => $svcpart,
569       map { $_ => $packet->{$_} }
570         qw( username _password sec_phrase popnum ),
571     };
572
573     my @acct_snarf;
574     my $snarfnum = 1;
575     while (    exists($packet->{"snarf_machine$snarfnum"})
576             && length($packet->{"snarf_machine$snarfnum"}) ) {
577       my $acct_snarf = new FS::acct_snarf ( {
578         'machine'   => $packet->{"snarf_machine$snarfnum"},
579         'protocol'  => $packet->{"snarf_protocol$snarfnum"},
580         'username'  => $packet->{"snarf_username$snarfnum"},
581         '_password' => $packet->{"snarf_password$snarfnum"},
582       } );
583       $snarfnum++;
584       push @acct_snarf, $acct_snarf;
585     }
586     $svc->child_objects( \@acct_snarf );
587
588     push @svc, $svc;
589
590   } elsif ( $svc_x eq 'svc_phone' ) {
591
592     my $svc = new FS::svc_phone ( {
593       'svcpart' => $svcpart,
594        map { $_ => $packet->{$_} }
595          qw( countrycode phonenum sip_password pin ),
596     } );
597
598     push @svc, $svc;
599
600   } else {
601     die "unknown signup service $svc_x";
602   }
603   my $y = $svc[0]->setdefault; # arguably should be in new method
604   return { 'error' => $y } if $y && !ref($y);
605
606   if ($packet->{'mac_addr'} && $conf->exists('signup_server-mac_addr_svcparts'))
607   {
608
609     my %mac_addr_svcparts = map { $_ => 1 }
610                             $conf->config('signup_server-mac_addr_svcparts');
611     my @pkg_svc = grep { $_->quantity && $mac_addr_svcparts{$_->svcpart} }
612                   $cust_pkg->part_pkg->pkg_svc;
613
614     return { 'error' => 'No service defined to assign mac address' }
615       unless @pkg_svc;
616
617     my $svc = new FS::svc_acct {
618       'svcpart'   => $pkg_svc[0]->svcpart, #multiple matches? alas..
619       'username'  => $packet->{'mac_addr'},
620       '_password' => '', #blank as requested (set passwordmin to 0)
621     };
622
623     my $y = $svc->setdefault; # arguably should be in new method
624     return { 'error' => $y } if $y && !ref($y);
625
626     push @svc, $svc;
627
628   }
629
630   #$error = $svc->check;
631   #return { 'error' => $error } if $error;
632
633   #setup a job dependancy to delay provisioning
634   my $placeholder = new FS::queue ( {
635     'job'    => 'FS::ClientAPI::Signup::__placeholder',
636     'status' => 'locked',
637   } );
638   my $error = $placeholder->insert;
639   return { 'error' => $error } if $error;
640
641   use Tie::RefHash;
642   tie my %hash, 'Tie::RefHash';
643   %hash = ( $cust_pkg => \@svc );
644   #msgcat
645   $error = $cust_main->insert(
646     \%hash,
647     \@invoicing_list,
648     'depend_jobnum' => $placeholder->jobnum,
649   );
650   if ( $error ) {
651     my $perror = $placeholder->delete;
652     $error .= " (Additionally, error removing placeholder: $perror)" if $perror;
653     return { 'error' => $error };
654   }
655
656   if ( $conf->exists('signup_server-realtime') ) {
657
658     #warn "$me Billing customer...\n" if $Debug;
659
660     my $bill_error = $cust_main->bill;
661     #warn "$me error billing new customer: $bill_error"
662     #  if $bill_error;
663
664     $bill_error = $cust_main->apply_payments_and_credits;
665     #warn "$me error applying payments and credits for".
666     #     " new customer: $bill_error"
667     #  if $bill_error;
668
669     $bill_error = $cust_main->realtime_collect(
670        method        => FS::payby->payby2bop( $packet->{payby} ),
671        depend_jobnum => $placeholder->jobnum,
672     );
673     #warn "$me error collecting from new customer: $bill_error"
674     #  if $bill_error;
675
676     if ($bill_error && ref($bill_error) eq 'HASH') {
677       return { 'error' => '_collect',
678                ( map { $_ => $bill_error->{$_} }
679                  qw(popup_url reference collectitems)
680                ),
681                amount => $cust_main->balance,
682              };
683     }
684
685     $bill_error = $cust_main->apply_payments_and_credits;
686     #warn "$me error applying payments and credits for".
687     #     " new customer: $bill_error"
688     #  if $bill_error;
689
690     if ( $cust_main->balance > 0 ) {
691
692       #this makes sense.  credit is "un-doing" the invoice
693       $cust_main->credit( $cust_main->balance, 'signup server decline',
694                           'reason_type' => $conf->config('signup_credit_type'),
695                         );
696       $cust_main->apply_credits;
697
698       #should check list for errors...
699       #$cust_main->suspend;
700       local $FS::svc_Common::noexport_hack = 1;
701       $cust_main->cancel('quiet'=>1);
702
703       my $perror = $placeholder->depended_delete;
704       warn "error removing provisioning jobs after decline: $perror" if $perror;
705       unless ( $perror ) {
706         $perror = $placeholder->delete;
707         warn "error removing placeholder after decline: $perror" if $perror;
708       }
709
710       return { 'error' => '_decline' };
711     }
712
713   }
714
715   if ( $reg_code ) {
716     $error = $reg_code->delete;
717     return { 'error' => $error } if $error;
718   }
719
720   $error = $placeholder->delete;
721   return { 'error' => $error } if $error;
722
723   my %return = ( 'error'          => '',
724                  'signup_service' => $svc_x,
725                );
726
727   if ( $svc_x eq 'svc_acct' ) {
728     $return{$_} = $svc[0]->$_() for qw( username _password );
729   } elsif ( $svc_x eq 'svc_phone' ) {
730     $return{$_} = $svc[0]->$_() for qw( countrycode phonenum sip_password pin );
731   } else {
732     die "unknown signup service $svc_x";
733   }
734
735   return \%return;
736
737 }
738
739 sub capture_payment {
740   my $packet = shift;
741
742   warn "$me capture_payment called on $packet\n" if $DEBUG;
743
744   ###
745   # identify processor/gateway from called back URL
746   ###
747
748   my $conf = new FS::Conf;
749
750   my $url = $packet->{url};
751   my $payment_gateway =
752     qsearchs('payment_gateway', { 'gateway_callback_url' => popurl(0, $url) } );
753
754   unless ($payment_gateway) {
755
756     my ( $processor, $login, $password, $action, @bop_options ) =
757       $conf->config('business-onlinepayment');
758     $action ||= 'normal authorization';
759     pop @bop_options if scalar(@bop_options) % 2 && $bop_options[-1] =~ /^\s*$/;
760     die "No real-time processor is enabled - ".
761         "did you set the business-onlinepayment configuration value?\n"
762       unless $processor;
763
764     $payment_gateway = new FS::payment_gateway( {
765       gateway_namespace => $conf->config('business-onlinepayment-namespace'),
766       gateway_module    => $processor,
767       gateway_username  => $login,
768       gateway_password  => $password,
769       gateway_action    => $action,
770       options   => [ ( @bop_options ) ],
771     });
772
773   }
774  
775   die "No real-time third party processor is enabled - ".
776       "did you set the business-onlinepayment configuration value?\n*"
777     unless $payment_gateway->gateway_namespace eq 'Business::OnlineThirdPartyPayment';
778
779   ###
780   # locate pending transaction
781   ###
782
783   eval "use Business::OnlineThirdPartyPayment";
784   die $@ if $@;
785
786   my $transaction =
787     new Business::OnlineThirdPartyPayment( $payment_gateway->gateway_module,
788                                            @{ [ $payment_gateway->options ] },
789                                          );
790
791   my $paypendingnum = $transaction->reference($packet->{data});
792
793   my $cust_pay_pending =
794     qsearchs('cust_pay_pending', { paypendingnum => $paypendingnum } );
795
796   unless ($cust_pay_pending) {
797     my $bill_error = "No payment is being processed with id $paypendingnum".
798                      "; Transaction aborted.";
799     return { error => '_decline', bill_error => $bill_error };
800   }
801
802   if ($cust_pay_pending->status ne 'pending') {
803     my $bill_error = "Payment with id $paypendingnum is not pending, but ".
804                      $cust_pay_pending->status.  "; Transaction aborted.";
805     return { error => '_decline', bill_error => $bill_error };
806   }
807
808   my $cust_main = $cust_pay_pending->cust_main;
809   my $bill_error =
810     $cust_main->realtime_botpp_capture( $cust_pay_pending, %{$packet->{data}} );
811
812   return { 'error'      => ( $bill_error->{bill_error} ? '_decline' : '' ),
813            %$bill_error,
814          };
815
816 }
817
818 1;