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