c968d3b2ec5a1dcc934c50af838adbd6bd2c1a84
[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 use FS::banned_pay;
26
27 $DEBUG = 0;
28 $me = '[FS::ClientAPI::Signup]';
29
30 sub clear_cache {
31   warn "$me clear_cache called\n" if $DEBUG;
32   my $cache = new FS::ClientAPI_SessionCache( {
33       'namespace' => 'FS::ClientAPI::Signup',
34   } );
35   $cache->clear();
36   return {};
37 }
38
39 sub signup_info {
40   my $packet = shift;
41
42   warn "$me signup_info called on $packet\n" if $DEBUG;
43
44   my $conf = new FS::Conf;
45   my $svc_x = $conf->config('signup_server-service') || 'svc_acct';
46
47   my $cache = new FS::ClientAPI_SessionCache( {
48     'namespace' => 'FS::ClientAPI::Signup',
49   } );
50   my $signup_info_cache = $cache->get('signup_info_cache');
51
52   if ( $signup_info_cache ) {
53
54     warn "$me loading cached signup info\n" if $DEBUG > 1;
55
56   } else {
57
58     warn "$me populating signup info cache\n" if $DEBUG > 1;
59
60     my $agentnum2part_pkg = 
61       {
62         map {
63           my $agent = $_;
64           my $href = $agent->pkgpart_hashref;
65           $agent->agentnum =>
66             [
67               map { { 'payby'       => [ $_->payby ],
68                       'freq_pretty' => $_->freq_pretty,
69                       'options'     => { $_->options },
70                       %{$_->hashref}
71                   } }
72                 grep { $_->svcpart($svc_x)
73                        && ( $href->{ $_->pkgpart }
74                             || ( $_->agentnum
75                                  && $_->agentnum == $agent->agentnum
76                                )
77                           )
78                      }
79                   qsearch( 'part_pkg', { 'disabled' => '' } )
80             ];
81         } qsearch('agent', { 'disabled' => '' })
82       };
83
84     my $msgcat = { map { $_=>gettext($_) }
85                        qw( passwords_dont_match invalid_card unknown_card_type
86                            not_a empty_password illegal_or_empty_text )
87                  };
88     warn "msgcat: ". Dumper($msgcat). "\n" if $DEBUG > 2;
89
90     my $label = { map { $_ => FS::Msgcat::_gettext($_) }
91                       qw( stateid stateid_state )
92                 };
93     warn "label: ". Dumper($label). "\n" if $DEBUG > 2;
94
95     my @agent_fields = qw( agentnum agent );
96
97     my @bools = qw( emailinvoiceonly security_phrase );
98
99     my @signup_bools = qw( no_company recommend_daytime recommend_email );
100
101     my @signup_server_scalars = qw( default_pkgpart default_svcpart default_domsvc );
102
103     my @selfservice_textareas = qw( head body_header body_footer );
104
105     my @selfservice_scalars = qw(
106       body_bgcolor box_bgcolor
107       text_color link_color vlink_color hlink_color alink_color
108       font title_color title_align title_size menu_bgcolor menu_fontsize
109     );
110
111     #XXX my @selfservice_bools = qw(
112     #  menu_skipblanks menu_skipheadings menu_nounderline
113     #);
114
115     #my $selfservice_binaries = qw(
116     #  title_left_image title_right_image
117     #  menu_top_image menu_body_image menu_bottom_image
118     #);
119
120     $signup_info_cache = {
121
122       'cust_main_county' => [ map $_->hashref,
123                                   qsearch('cust_main_county', {} )
124                             ],
125
126       'agent' => [ map { my $agent = $_;
127                          +{ map { $_ => $agent->get($_) } @agent_fields }
128                        }
129                        qsearch('agent', { 'disabled' => '' } )
130                  ],
131
132       'part_referral' => [ map $_->hashref,
133                                qsearch('part_referral', { 'disabled' => '' } )
134                          ],
135
136       'agentnum2part_pkg' => $agentnum2part_pkg,
137
138       'svc_acct_pop' => [ map $_->hashref, qsearch('svc_acct_pop',{} ) ],
139
140       'emailinvoiceonly' => $conf->exists('emailinvoiceonly'),
141
142       'security_phrase' => $conf->exists('security_phrase'),
143
144       'nomadix' => $conf->exists('signup_server-nomadix'),
145
146       'payby' => [ $conf->config('signup_server-payby') ],
147
148       'payby_longname' => [ map { FS::payby->longname($_) } 
149                             $conf->config('signup_server-payby') ],
150
151       'card_types' => card_types(),
152
153       ( map { $_ => $conf->exists("signup-$_") } @signup_bools ),
154
155       ( map { $_ => scalar($conf->config("signup_server-$_")) }
156             @signup_server_scalars
157       ),
158
159       ( map { $_ => join("\n", $conf->config("selfservice-$_")) }
160             @selfservice_textareas
161       ),
162       ( map { $_ => scalar($conf->config("selfservice-$_")) }
163             @selfservice_scalars
164       ),
165
166       #( map { $_ => scalar($conf->config_binary("selfservice-$_")) }
167       #      @selfservice_binaries
168       #),
169
170       'agentnum2part_pkg'  => $agentnum2part_pkg,
171       'svc_acct_pop'       => [ map $_->hashref, qsearch('svc_acct_pop',{} ) ],
172       'nomadix'            => $conf->exists('signup_server-nomadix'),
173       'payby'              => [ $conf->config('signup_server-payby') ],
174       'card_types'         => card_types(),
175       'paytypes'           => [ @FS::cust_main::paytypes ],
176       'cvv_enabled'        => 1,
177       'require_cvv'        => $conf->exists('signup-require_cvv'),
178       'stateid_enabled'    => $conf->exists('show_stateid'),
179       'paystate_enabled'   => $conf->exists('show_bankstate'),
180       'ship_enabled'       => 1,
181       'msgcat'             => $msgcat,
182       'label'              => $label,
183       'statedefault'       => scalar($conf->config('statedefault')) || 'CA',
184       'countrydefault'     => scalar($conf->config('countrydefault')) || 'US',
185       'refnum'             => scalar($conf->config('signup_server-default_refnum')),
186       'signup_service'     => $svc_x,
187       'company_name'       => scalar($conf->config('company_name')),
188       #per-agent?
189       'logo'               => scalar($conf->config_binary('logo.png')),
190       'prepaid_template_custnum' => $conf->exists('signup_server-prepaid-template-custnum'),
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       or return { 'error' => "Self-service agent #$agentnum does not exist" };
322     warn "$me has agent $agent\n" if $DEBUG > 1;
323     my @paybys = @{ $signup_info->{'payby'} };
324     $signup_info->{'hide_payment_fields'} = [];
325
326     my $gatewaynum = $conf->config('selfservice-payment_gateway');
327     my $force_gateway;
328     if ( $gatewaynum ) {
329       $force_gateway = qsearchs('payment_gateway', { gatewaynum => $gatewaynum });
330       warn "using forced gateway #$gatewaynum - " .
331         $force_gateway->gateway_username . '@' . $force_gateway->gateway_module
332         if $DEBUG > 1;
333       die "configured gatewaynum $gatewaynum not found!" if !$force_gateway;
334     }
335     foreach my $payby (@paybys) {
336       warn "$me checking $payby payment fields\n" if $DEBUG > 1;
337       my $hide = 0;
338       if ( FS::payby->realtime($payby) ) {
339         my $gateway = $force_gateway || 
340           $agent->payment_gateway( 'method'  => FS::payby->payby2bop($payby),
341                                    'nofatal' => 1,
342                                  );
343         if ( $gateway && $gateway->gateway_namespace
344                     eq 'Business::OnlineThirdPartyPayment'
345            ) {
346           warn "$me hiding $payby payment fields\n" if $DEBUG > 1;
347           $hide = 1;
348         }
349       }
350       push @{$signup_info->{'hide_payment_fields'}}, $hide;
351     } # foreach $payby
352     warn "$me done setting agent-specific payment flag\n" if $DEBUG > 1;
353
354     warn "$me setting agent-specific package list\n" if $DEBUG > 1;
355     $signup_info->{'part_pkg'} = $signup_info->{'agentnum2part_pkg'}{$agentnum}
356       unless @{ $signup_info->{'part_pkg'} };
357     warn "$me done setting agent-specific package list\n" if $DEBUG > 1;
358
359     warn "$me setting agent-specific adv. source list\n" if $DEBUG > 1;
360     $signup_info->{'part_referral'} =
361       [
362         map { $_->hashref }
363           qsearch( {
364                      'table'     => 'part_referral',
365                      'hashref'   => { 'disabled' => '' },
366                      'extra_sql' => "AND (    agentnum = $agentnum  ".
367                                     "      OR agentnum IS NULL    ) ",
368                    },
369                  )
370       ];
371     warn "$me done setting agent-specific adv. source list\n" if $DEBUG > 1;
372
373     $signup_info->{'agent_name'} = $agent->agent;
374
375     $signup_info->{'company_name'} = $conf->config('company_name', $agentnum);
376
377     #some of the above could probably be cached, too
378
379     my $signup_info_cache_agent = $cache->get("signup_info_cache_agent$agentnum");
380
381     if ( $signup_info_cache_agent ) {
382
383       warn "$me loading cached signup info for agentnum $agentnum\n"
384         if $DEBUG > 1;
385
386     } else {
387
388       warn "$me populating signup info cache for agentnum $agentnum\n"
389         if $DEBUG > 1;
390
391       $signup_info_cache_agent = {
392         #( map { $_ => scalar( $conf->config($_, $agentnum) ) }
393         #  qw( company_name ) ),
394         ( map { $_ => scalar( $conf->config("selfservice-$_", $agentnum ) ) }
395           qw( body_bgcolor box_bgcolor menu_bgcolor ) ),
396         ( map { $_ => join("\n", $conf->config("selfservice-$_", $agentnum ) ) }
397           qw( head body_header body_footer ) ),
398         ( map { $_ => join("\n", $conf->config("signup_server-$_", $agentnum ) ) }
399           qw( terms_of_service ) ),
400
401         ( map { $_ => scalar($conf->exists($_, $agentnum)) } 
402           qw(cust_main-require_phone agent-ship_address) ),
403       };
404
405       if ( $signup_info_cache_agent->{'agent-ship_address'} 
406            && $agent->agent_cust_main ) {
407
408         my $cust_main = $agent->agent_cust_main;
409         my $location = $cust_main->ship_location;
410         $signup_info_cache_agent->{"ship_$_"} = $location->get($_)
411           foreach qw( address1 city county state zip country );
412
413       }
414
415       $cache->set("signup_info_cache_agent$agentnum", $signup_info_cache_agent);
416
417     }
418
419     $signup_info->{$_} = $signup_info_cache_agent->{$_}
420       foreach keys %$signup_info_cache_agent;
421
422   }
423   # else {
424   # delete $signup_info->{'part_pkg'};
425   #}
426
427   warn "$me sorting package list\n" if $DEBUG > 1;
428   $signup_info->{'part_pkg'} = [ sort { $a->{pkg} cmp $b->{pkg} }  # case?
429                                       @{ $signup_info->{'part_pkg'} }
430                                ];
431   warn "$me done sorting package list\n" if $DEBUG > 1;
432
433   if ( exists $packet->{'session_id'} ) {
434     my $agent_signup_info = { %$signup_info };
435     delete $agent_signup_info->{agentnum2part_pkg};
436     $agent_signup_info->{'agent'} = $session->{'agent'};
437     return $agent_signup_info;
438   } 
439   elsif ( exists $packet->{'keys'} ) {
440     my @keys = @{ $packet->{'keys'} };
441     return { map { $_ => $signup_info->{$_} } @keys };
442   }
443   else {
444     return $signup_info;
445   }
446
447 }
448
449 sub domain_select_hash {
450   my $packet = shift;
451
452   my $response = {};
453
454   if ($packet->{pkgpart}) {
455     my $part_pkg = qsearchs('part_pkg' => { 'pkgpart' => $packet->{pkgpart} } );
456     #$packet->{svcpart} = $part_pkg->svcpart('svc_acct')
457     $packet->{svcpart} = $part_pkg->svcpart
458       if $part_pkg;
459   }
460
461   if ($packet->{svcpart}) {
462     my $part_svc = qsearchs('part_svc' => { 'svcpart' => $packet->{svcpart} } );
463     $response->{'domsvc'} = $part_svc->part_svc_column('domsvc')->columnvalue
464       if ($part_svc && $part_svc->part_svc_column('domsvc')->columnflag  eq 'D');
465   }
466
467   $response->{'domains'}
468     = { domain_select_hash FS::svc_acct( map { $_ => $packet->{$_} }
469                                                  qw(svcpart pkgnum)
470                                        ) };
471
472   $response;
473 }
474
475 sub new_customer {
476   my $packet = shift;
477
478   my $conf = new FS::Conf;
479   my $svc_x = $conf->config('signup_server-service') || 'svc_acct';
480
481   if ( $svc_x eq 'svc_acct' ) {
482   
483     #things that aren't necessary in base class, but are for signup server
484       #return "Passwords don't match"
485       #  if $hashref->{'_password'} ne $hashref->{'_password2'}
486     return { 'error' => gettext('empty_password') }
487       unless length($packet->{'_password'});
488     # a bit inefficient for large numbers of pops
489     return { 'error' => gettext('no_access_number_selected') }
490       unless $packet->{'popnum'} || !scalar(qsearch('svc_acct_pop',{} ));
491
492   }
493   elsif ( $svc_x eq 'svc_pbx' ) {
494     #possibly some validation will be needed
495   }
496
497   my $agentnum;
498   if ( exists $packet->{'session_id'} ) {
499     my $cache = new FS::ClientAPI_SessionCache( {
500       'namespace' => 'FS::ClientAPI::Agent',
501     } );
502     my $session = $cache->get($packet->{'session_id'});
503     if ( $session ) {
504       $agentnum = $session->{'agentnum'};
505     } else {
506       return { 'error' => "Can't resume session" }; #better error message
507     }
508   } else {
509     $agentnum = $packet->{agentnum}
510                 || $conf->config('signup_server-default_agentnum');
511   }
512
513   my ($bill_hash, $ship_hash);
514   foreach my $f (FS::cust_main->location_fields) {
515     # avoid having to change this in front-end code
516     $bill_hash->{$f} = $packet->{"bill_$f"} || $packet->{$f};
517     $ship_hash->{$f} = $packet->{"ship_$f"};
518   }
519
520   #shares some stuff with htdocs/edit/process/cust_main.cgi... take any
521   # common that are still here and library them.
522   my $template_custnum = $conf->config('signup_server-prepaid-template-custnum');
523   my $cust_main;
524   if ( $template_custnum && $packet->{prepaid_shortform} ) {
525
526     my $template_cust = qsearchs('cust_main', { 'custnum' => $template_custnum } );
527     return { 'error' => 'Configuration error' } unless $template_cust;
528     $cust_main = new FS::cust_main ( {
529       'agentnum'      => $agentnum,
530       'refnum'        => $packet->{refnum}
531                          || $conf->config('signup_server-default_refnum'),
532
533       ( map { $_ => $template_cust->$_ } qw( 
534               last first company daytime night fax 
535             )
536       ),
537
538       ( map { $_ => $packet->{$_} } qw(
539               ss stateid stateid_state
540
541               payby
542               payinfo paycvv paydate payname paystate paytype
543               paystart_month paystart_year payissue
544               payip
545
546               referral_custnum comments
547             )
548       ),
549
550     } );
551
552     $bill_hash = { $template_cust->bill_location->location_hash };
553     $ship_hash = { $template_cust->ship_location->location_hash };
554
555   } else {
556
557     $cust_main = new FS::cust_main ( {
558       #'custnum'          => '',
559       'agentnum'      => $agentnum,
560       'refnum'        => $packet->{refnum}
561                          || $conf->config('signup_server-default_refnum'),
562
563       map { $_ => $packet->{$_} } qw(
564         last first ss company 
565         daytime night fax stateid stateid_state
566         payby
567         payinfo paycvv paydate payname paystate paytype
568         paystart_month paystart_year payissue
569         payip
570         override_ban_warn
571         referral_custnum comments
572       ),
573
574     } );
575   }
576
577   my $bill_location = FS::cust_location->new($bill_hash);
578   my $ship_location;
579   my $agent = qsearchs('agent', { 'agentnum' => $agentnum } );
580   if ( $conf->exists('agent-ship_address', $agentnum) 
581     && $agent->agent_custnum ) {
582
583     my $agent_cust_main = $agent->agent_cust_main;
584     my $prefix = length($agent_cust_main->ship_last) ? 'ship_' : '';
585     $ship_location = FS::cust_location->new({ 
586         $agent_cust_main->ship_location->location_hash
587     });
588
589   }
590   # we don't have an equivalent of the "same" checkbox in selfservice
591   # so is there a ship address, and if so, is it different from the billing 
592   # address?
593   elsif ( length($ship_hash->{address1}) > 0 and
594           grep { $bill_hash->{$_} ne $ship_hash->{$_} } keys(%$ship_hash)
595          ) {
596
597     $ship_location = FS::cust_location->new( $ship_hash );
598   
599   }
600   else {
601     $ship_location = $bill_location;
602   }
603
604   $cust_main->set('bill_location' => $bill_location);
605   $cust_main->set('ship_location' => $ship_location);
606
607   return { 'error' => "Illegal payment type" }
608     unless grep { $_ eq $packet->{'payby'} }
609                 $conf->config('signup_server-payby');
610
611   if (FS::payby->realtime($packet->{payby})
612     and not $conf->exists('signup_server-third_party_as_card')) {
613     my $payby = $packet->{payby};
614
615     my $agent = qsearchs('agent', { 'agentnum' => $agentnum });
616     return { 'error' => "Unknown reseller" }
617       unless $agent;
618
619     my $gw;
620     my $gatewaynum = $conf->config('selfservice-payment_gateway');
621     if ( $gatewaynum ) {
622       $gw = qsearchs('payment_gateway', { gatewaynum => $gatewaynum });
623       die "configured gatewaynum $gatewaynum not found!" if !$gw;
624     }
625     else {
626       $gw = $agent->payment_gateway( 'method'  => FS::payby->payby2bop($payby),
627                                      'nofatal' => 1,
628                                     );
629     }
630
631     $cust_main->payby('BILL')   # MCRD better?
632       if $gw && $gw->gateway_namespace eq 'Business::OnlineThirdPartyPayment';
633   }
634
635   return { 'error' => "CVV2 is required" }
636     if $cust_main->payby =~ /^(CARD|DCRD)$/
637     && ! $cust_main->paycvv
638     && $conf->exists('signup-require_cvv');
639
640   $cust_main->payinfo($cust_main->daytime)
641     if $cust_main->payby eq 'LECB' && ! $cust_main->payinfo;
642
643   my @invoicing_list = $packet->{'invoicing_list'}
644                          ? split( /\s*\,\s*/, $packet->{'invoicing_list'} )
645                          : ();
646
647   $packet->{'pkgpart'} =~ /^(\d+)$/ or '' =~ /^()$/;
648   my $pkgpart = $1;
649   return { 'error' => 'Please select a package' } unless $pkgpart; #msgcat
650
651   my $part_pkg =
652     qsearchs( 'part_pkg', { 'pkgpart' => $pkgpart } )
653       or return { 'error' => "WARNING: unknown pkgpart: $pkgpart" };
654   my $svcpart = $part_pkg->svcpart($svc_x);
655
656   my $reg_code = '';
657   if ( $packet->{'reg_code'} ) {
658     $reg_code = qsearchs( 'reg_code', { 'code'     => $packet->{'reg_code'},
659                                         'agentnum' => $agentnum,             } )
660       or return { 'error' => 'Unknown registration code' };
661   }
662
663   my $cust_pkg = new FS::cust_pkg ( {
664     #later#'custnum' => $custnum,
665     'pkgpart'    => $packet->{'pkgpart'},
666     'promo_code' => $packet->{'promo_code'},
667     'reg_code'   => $packet->{'reg_code'},
668   } );
669   #my $error = $cust_pkg->check;
670   #return { 'error' => $error } if $error;
671
672   #should be all auto-magic and shit
673   my @svc = ();
674   if ( $svc_x eq 'svc_acct' ) {
675
676     my $svc = new FS::svc_acct {
677       'svcpart'   => $svcpart,
678       map { $_ => $packet->{$_} }
679         qw( username _password sec_phrase popnum domsvc ),
680     };
681
682     my @acct_snarf;
683     my $snarfnum = 1;
684     while (    exists($packet->{"snarf_machine$snarfnum"})
685             && length($packet->{"snarf_machine$snarfnum"}) ) {
686       my $acct_snarf = new FS::acct_snarf ( {
687         'machine'   => $packet->{"snarf_machine$snarfnum"},
688         'protocol'  => $packet->{"snarf_protocol$snarfnum"},
689         'username'  => $packet->{"snarf_username$snarfnum"},
690         '_password' => $packet->{"snarf_password$snarfnum"},
691       } );
692       $snarfnum++;
693       push @acct_snarf, $acct_snarf;
694     }
695     $svc->child_objects( \@acct_snarf );
696     push @svc, $svc;
697
698   } elsif ( $svc_x eq 'svc_phone' ) {
699
700     push @svc, new FS::svc_phone ( {
701       'svcpart' => $svcpart,
702        map { $_ => $packet->{$_} }
703          qw( countrycode phonenum sip_password pin ),
704     } );
705
706   } elsif ( $svc_x eq 'svc_pbx' ) {
707
708     push @svc, new FS::svc_pbx ( {
709         'svcpart' => $svcpart,
710         map { $_ => $packet->{$_} } 
711           qw( id title ),
712         } );
713   
714   } else {
715     die "unknown signup service $svc_x";
716   }
717
718   if ($packet->{'mac_addr'} && $conf->exists('signup_server-mac_addr_svcparts'))
719   {
720
721     my %mac_addr_svcparts = map { $_ => 1 }
722                             $conf->config('signup_server-mac_addr_svcparts');
723     my @pkg_svc = grep { $_->quantity && $mac_addr_svcparts{$_->svcpart} }
724                   $cust_pkg->part_pkg->pkg_svc;
725
726     return { 'error' => 'No service defined to assign mac address' }
727       unless @pkg_svc;
728
729     my $svc = new FS::svc_acct {
730       'svcpart'   => $pkg_svc[0]->svcpart, #multiple matches? alas..
731       'username'  => $packet->{'mac_addr'},
732       '_password' => '', #blank as requested (set passwordmin to 0)
733     };
734
735     push @svc, $svc;
736
737   }
738
739   foreach my $svc ( @svc ) {
740     my $y = $svc->setdefault; # arguably should be in new method
741     return { 'error' => $y } if $y && !ref($y);
742     #$error = $svc->check;
743     #return { 'error' => $error } if $error;
744   }
745
746   #setup a job dependancy to delay provisioning
747   my $placeholder = new FS::queue ( {
748     'job'    => 'FS::ClientAPI::Signup::__placeholder',
749     'status' => 'locked',
750   } );
751   my $error = $placeholder->insert;
752   return { 'error' => $error } if $error;
753
754   use Tie::RefHash;
755   tie my %hash, 'Tie::RefHash';
756   %hash = ( $cust_pkg => \@svc );
757   #msgcat
758   $error = $cust_main->insert(
759     \%hash,
760     \@invoicing_list,
761     'depend_jobnum' => $placeholder->jobnum,
762   );
763   if ( $error ) {
764     my $perror = $placeholder->delete;
765     $error .= " (Additionally, error removing placeholder: $perror)" if $perror;
766     return { 'error' => $error };
767   }
768
769   if ( $conf->exists('signup_server-realtime') ) {
770
771     #warn "$me Billing customer...\n" if $Debug;
772
773     my $bill_error = $cust_main->bill( 'depend_jobnum'=>$placeholder->jobnum );
774     #warn "$me error billing new customer: $bill_error"
775     #  if $bill_error;
776
777     $bill_error = $cust_main->apply_payments_and_credits;
778     #warn "$me error applying payments and credits for".
779     #     " new customer: $bill_error"
780     #  if $bill_error;
781
782     unless ( $packet->{payby} eq 'PREPAY' ) {
783       $bill_error = $cust_main->realtime_collect(
784          method        => FS::payby->payby2bop( $packet->{payby} ),
785          depend_jobnum => $placeholder->jobnum,
786          selfservice   => 1,
787       );
788       #warn "$me error collecting from new customer: $bill_error"
789       #  if $bill_error;
790     }
791
792     if ($bill_error && ref($bill_error) eq 'HASH') {
793       return { 'error' => '_collect',
794                ( map { $_ => $bill_error->{$_} }
795                  qw(popup_url reference collectitems)
796                ),
797                amount => $cust_main->balance,
798              };
799     }
800
801     $bill_error = $cust_main->apply_payments_and_credits;
802     #warn "$me error applying payments and credits for".
803     #     " new customer: $bill_error"
804     #  if $bill_error;
805
806     if ( $cust_main->balance > 0 ) {
807
808       #this makes sense.  credit is "un-doing" the invoice
809       $cust_main->credit( $cust_main->balance, 'signup server decline',
810                           'reason_type' => $conf->config('signup_credit_type'),
811                         );
812       $cust_main->apply_credits;
813
814       #should check list for errors...
815       #$cust_main->suspend;
816       local $FS::svc_Common::noexport_hack = 1;
817       $cust_main->cancel('quiet'=>1);
818
819       my $perror = $placeholder->depended_delete;
820       warn "error removing provisioning jobs after decline: $perror" if $perror;
821       unless ( $perror ) {
822         $perror = $placeholder->delete;
823         warn "error removing placeholder after decline: $perror" if $perror;
824       }
825
826       return { 'error' => '_decline' };
827     }
828
829   }
830
831   if ( $reg_code ) {
832     $error = $reg_code->delete;
833     return { 'error' => $error } if $error;
834   }
835
836   $error = $placeholder->delete;
837   return { 'error' => $error } if $error;
838
839   if ( $conf->exists('signup-duplicate_cc-warn_hours') ) {
840     my $hours = $conf->config('signup-duplicate_cc-warn_hours');
841     my $ban = new FS::banned_pay $cust_main->_new_banned_pay_hashref;
842     $ban->end_date( int( time + $hours*3600 ) );
843     $ban->bantype('warn');
844     $ban->reason('signup-duplicate_cc-warn_hours');
845     $error = $ban->insert;
846     warn "WARNING: error inserting temporary banned_pay for ".
847          " signup-duplicate_cc-warn_hours (proceeding anyway): $error"
848       if $error;
849   }
850
851   my %return = ( 'error'          => '',
852                  'signup_service' => $svc_x,
853                  'custnum'        => $cust_main->custnum,
854                );
855
856   if ( $svc[0] ) {
857
858     $return{'svcnum'} = $svc[0]->svcnum;
859
860     if ( $svc_x eq 'svc_acct' ) {
861       $return{$_} = $svc[0]->$_() for qw( username _password );
862     } elsif ( $svc_x eq 'svc_phone' ) {
863       $return{$_} = $svc[0]->$_() for qw(countrycode phonenum sip_password pin);
864     } elsif ( $svc_x eq 'svc_pbx' ) {
865       #$return{$_} = $svc[0]->$_() for qw( ) #nothing yet
866      } else {
867       return {'error' => "configuration error: unknown signup service $svc_x"};
868       #die "unknown signup service $svc_x";
869       # return an error that's visible to someone somewhere
870     }
871
872   }
873
874   return \%return;
875
876 }
877
878 sub capture_payment {
879   my $packet = shift;
880
881   warn "$me capture_payment called on $packet\n" if $DEBUG;
882
883   ###
884   # identify processor/gateway from called back URL
885   ###
886
887   my $conf = new FS::Conf;
888
889   my $payment_gateway;
890   if ( my $gwnum = $conf->config('selfservice-payment_gateway') ) {
891     $payment_gateway = qsearchs('payment_gateway', { 'gatewaynum' => $gwnum })
892       or die "configured gatewaynum $gwnum not found!";
893   }
894   else {
895     my $url = $packet->{url};
896
897     $payment_gateway = qsearchs('payment_gateway', 
898         { 'gateway_callback_url' => popurl(0, $url) } 
899       );
900     if (!$payment_gateway) { 
901
902       my ( $processor, $login, $password, $action, @bop_options ) =
903         $conf->config('business-onlinepayment');
904       $action ||= 'normal authorization';
905       pop @bop_options if scalar(@bop_options) % 2 && $bop_options[-1] =~ /^\s*$/;
906       die "No real-time processor is enabled - ".
907           "did you set the business-onlinepayment configuration value?\n"
908         unless $processor;
909
910       $payment_gateway = new FS::payment_gateway( {
911         gateway_namespace => $conf->config('business-onlinepayment-namespace'),
912         gateway_module    => $processor,
913         gateway_username  => $login,
914         gateway_password  => $password,
915         gateway_action    => $action,
916         options   => [ ( @bop_options ) ],
917       });
918     }
919   }
920  
921   die "No real-time third party processor is enabled - ".
922       "did you set the business-onlinepayment configuration value?\n*"
923     unless $payment_gateway->gateway_namespace eq 'Business::OnlineThirdPartyPayment';
924
925   ###
926   # locate pending transaction
927   ###
928
929   eval "use Business::OnlineThirdPartyPayment";
930   die $@ if $@;
931
932   my $transaction =
933     new Business::OnlineThirdPartyPayment( $payment_gateway->gateway_module,
934                                            @{ [ $payment_gateway->options ] },
935                                          );
936
937   my $paypendingnum = $transaction->reference($packet->{data});
938
939   my $cust_pay_pending =
940     qsearchs('cust_pay_pending', { paypendingnum => $paypendingnum } );
941
942   unless ($cust_pay_pending) {
943     my $bill_error = "No payment is being processed with id $paypendingnum".
944                      "; Transaction aborted.";
945     return { error => '_decline', bill_error => $bill_error };
946   }
947
948   if ($cust_pay_pending->status ne 'thirdparty') {
949     my $bill_error = "Payment with id $paypendingnum is not thirdparty, but ".
950                      $cust_pay_pending->status.  "; Transaction aborted.";
951     return { error => '_decline', bill_error => $bill_error };
952   }
953
954   my $cust_main = $cust_pay_pending->cust_main;
955   if ( $packet->{cancel} ) {
956     # the user has chosen not to make this payment
957     # (probably should be a separate API call, but I don't want to duplicate
958     # all of the above...which should eventually go away)
959     my $error = $cust_pay_pending->delete;
960     # don't show any errors related to this; they're not meaningful
961     warn "error canceling pending payment $paypendingnum: $error\n" if $error;
962     return { 'error'      => '_cancel',
963              'session_id' => $cust_pay_pending->session_id };
964   } else {
965     # create the payment
966     my $bill_error =
967       $cust_main->realtime_botpp_capture( $cust_pay_pending, 
968         %{$packet->{data}},
969         apply => 1,
970     );
971
972     return { 'error'      => ( $bill_error->{bill_error} ? '_decline' : '' ),
973              %$bill_error,
974            };
975   }
976
977 }
978
979 1;