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