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