Merge branch 'master' of git.freeside.biz:/home/git/freeside
[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 );
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       'stateid_enabled'    => $conf->exists('show_stateid'),
178       'paystate_enabled'   => $conf->exists('show_bankstate'),
179       'ship_enabled'       => 1,
180       'msgcat'             => $msgcat,
181       'label'              => $label,
182       'statedefault'       => scalar($conf->config('statedefault')) || 'CA',
183       'countrydefault'     => scalar($conf->config('countrydefault')) || 'US',
184       'refnum'             => scalar($conf->config('signup_server-default_refnum')),
185       'signup_service'     => $svc_x,
186       'company_name'       => scalar($conf->config('company_name')),
187       #per-agent?
188       'logo'               => scalar($conf->config_binary('logo.png')),
189       'prepaid_template_custnum' => $conf->exists('signup_server-prepaid-template-custnum'),
190     };
191
192     $cache->set('signup_info_cache', $signup_info_cache);
193
194   }
195
196   my $signup_info = { %$signup_info_cache };
197   warn "$me signup info loaded\n" if $DEBUG > 1;
198   warn Dumper($signup_info). "\n" if $DEBUG > 2;
199
200   my @addl = qw( signup_server-classnum2 signup_server-classnum3 );
201
202   if ( grep { $conf->exists($_) } @addl ) {
203   
204     $signup_info->{optional_packages} = [];
205
206     foreach my $addl ( @addl ) {
207
208       warn "$me adding optional package info\n" if $DEBUG > 1;
209
210       my $classnum = $conf->config($addl) or next;
211
212       my @pkgs = map { {
213                          'freq_pretty' => $_->freq_pretty,
214                          'options'     => { $_->options },
215                          %{ $_->hashref }
216                        };
217                      }
218                      qsearch( 'part_pkg', { classnum => $classnum } );
219
220       push @{$signup_info->{optional_packages}}, \@pkgs;
221
222       warn "$me done adding opt. package info for $classnum\n" if $DEBUG > 1;
223
224     }
225
226   }
227
228   my $agentnum = $packet->{'agentnum'}
229                  || $conf->config('signup_server-default_agentnum');
230   $agentnum =~ /^(\d*)$/ or die "illegal agentnum";
231   $agentnum = $1;
232
233   my $session = '';
234   if ( exists $packet->{'session_id'} ) {
235
236     warn "$me loading agent session\n" if $DEBUG > 1;
237     my $cache = new FS::ClientAPI_SessionCache( {
238       'namespace' => 'FS::ClientAPI::Agent',
239     } );
240     $session = $cache->get($packet->{'session_id'});
241     if ( $session ) {
242       $agentnum = $session->{'agentnum'};
243     } else {
244       return { 'error' => "Can't resume session" }; #better error message
245     }
246     warn "$me done loading agent session\n" if $DEBUG > 1;
247
248   } elsif ( exists $packet->{'customer_session_id'} ) {
249
250     warn "$me loading customer session\n" if $DEBUG > 1;
251     my $cache = new FS::ClientAPI_SessionCache( {
252       'namespace' => 'FS::ClientAPI::MyAccount',
253     } );
254     $session = $cache->get($packet->{'customer_session_id'});
255     if ( $session ) {
256       my $custnum = $session->{'custnum'};
257       my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum });
258       return { 'error' => "Can't find your customer record" } unless $cust_main;
259       $agentnum = $cust_main->agentnum;
260     } else {
261       return { 'error' => "Can't resume session" }; #better error message
262     }
263     warn "$me done loading customer session\n" if $DEBUG > 1;
264
265   }
266
267   $signup_info->{'part_pkg'} = [];
268
269   if ( $packet->{'reg_code'} ) {
270
271     warn "$me setting package list via reg_code\n" if $DEBUG > 1;
272
273     $signup_info->{'part_pkg'} = 
274       [ map { { 'payby'       => [ $_->payby ],
275                 'freq_pretty' => $_->freq_pretty,
276                 'options'     => { $_->options },
277                 %{$_->hashref}
278               };
279             }
280           grep { $_->svcpart($svc_x) }
281           map { $_->part_pkg }
282             qsearchs( 'reg_code', { 'code'     => $packet->{'reg_code'},
283                                     'agentnum' => $agentnum,              } )
284
285       ];
286
287     $signup_info->{'error'} = 'Unknown registration code'
288       unless @{ $signup_info->{'part_pkg'} };
289
290     warn "$me done setting package list via reg_code\n" if $DEBUG > 1;
291
292   } elsif ( $packet->{'promo_code'} ) {
293
294     warn "$me setting package list via promo_code\n" if $DEBUG > 1;
295
296     $signup_info->{'part_pkg'} =
297       [ map { { 'payby'   => [ $_->payby ],
298                 'freq_pretty' => $_->freq_pretty,
299                 'options'     => { $_->options },
300                 %{$_->hashref}
301             } }
302           grep { $_->svcpart($svc_x) }
303             qsearch( 'part_pkg', { 'promo_code' => {
304                                      op=>'ILIKE',
305                                      value=>$packet->{'promo_code'}
306                                    },
307                                    'disabled'   => '',                  } )
308       ];
309
310     $signup_info->{'error'} = 'Unknown promotional code'
311       unless @{ $signup_info->{'part_pkg'} };
312
313     warn "$me done setting package list via promo_code\n" if $DEBUG > 1;
314   }
315
316   if ( $agentnum ) {
317
318     warn "$me setting agent-specific payment flag\n" if $DEBUG > 1;
319     my $agent = qsearchs('agent', { 'agentnum' => $agentnum } )
320       or return { 'error' => "Self-service agent #$agentnum does not exist" };
321     warn "$me has agent $agent\n" if $DEBUG > 1;
322     my @paybys = @{ $signup_info->{'payby'} };
323     $signup_info->{'hide_payment_fields'} = [];
324
325     my $gatewaynum = $conf->config('selfservice-payment_gateway');
326     my $force_gateway;
327     if ( $gatewaynum ) {
328       $force_gateway = qsearchs('payment_gateway', { gatewaynum => $gatewaynum });
329       warn "using forced gateway #$gatewaynum - " .
330         $force_gateway->gateway_username . '@' . $force_gateway->gateway_module
331         if $DEBUG > 1;
332       die "configured gatewaynum $gatewaynum not found!" if !$force_gateway;
333     }
334     foreach my $payby (@paybys) {
335       warn "$me checking $payby payment fields\n" if $DEBUG > 1;
336       my $hide = 0;
337       if ( FS::payby->realtime($payby) ) {
338         my $gateway = $force_gateway || 
339           $agent->payment_gateway( 'method'  => FS::payby->payby2bop($payby),
340                                    'nofatal' => 1,
341                                  );
342         if ( $gateway && $gateway->gateway_namespace
343                     eq 'Business::OnlineThirdPartyPayment'
344            ) {
345           warn "$me hiding $payby payment fields\n" if $DEBUG > 1;
346           $hide = 1;
347         }
348       }
349       push @{$signup_info->{'hide_payment_fields'}}, $hide;
350     } # foreach $payby
351     warn "$me done setting agent-specific payment flag\n" if $DEBUG > 1;
352
353     warn "$me setting agent-specific package list\n" if $DEBUG > 1;
354     $signup_info->{'part_pkg'} = $signup_info->{'agentnum2part_pkg'}{$agentnum}
355       unless @{ $signup_info->{'part_pkg'} };
356     warn "$me done setting agent-specific package list\n" if $DEBUG > 1;
357
358     warn "$me setting agent-specific adv. source list\n" if $DEBUG > 1;
359     $signup_info->{'part_referral'} =
360       [
361         map { $_->hashref }
362           qsearch( {
363                      'table'     => 'part_referral',
364                      'hashref'   => { 'disabled' => '' },
365                      'extra_sql' => "AND (    agentnum = $agentnum  ".
366                                     "      OR agentnum IS NULL    ) ",
367                    },
368                  )
369       ];
370     warn "$me done setting agent-specific adv. source list\n" if $DEBUG > 1;
371
372     $signup_info->{'agent_name'} = $agent->agent;
373
374     $signup_info->{'company_name'} = $conf->config('company_name', $agentnum);
375
376     #some of the above could probably be cached, too
377
378     my $signup_info_cache_agent = $cache->get("signup_info_cache_agent$agentnum");
379
380     if ( $signup_info_cache_agent ) {
381
382       warn "$me loading cached signup info for agentnum $agentnum\n"
383         if $DEBUG > 1;
384
385     } else {
386
387       warn "$me populating signup info cache for agentnum $agentnum\n"
388         if $DEBUG > 1;
389
390       $signup_info_cache_agent = {
391         #( map { $_ => scalar( $conf->config($_, $agentnum) ) }
392         #  qw( company_name ) ),
393         ( map { $_ => scalar( $conf->config("selfservice-$_", $agentnum ) ) }
394           qw( body_bgcolor box_bgcolor menu_bgcolor ) ),
395         ( map { $_ => join("\n", $conf->config("selfservice-$_", $agentnum ) ) }
396           qw( head body_header body_footer ) ),
397         ( map { $_ => join("\n", $conf->config("signup_server-$_", $agentnum ) ) }
398           qw( terms_of_service ) ),
399
400         ( map { $_ => scalar($conf->exists($_, $agentnum)) } 
401           qw(cust_main-require_phone agent-ship_address) ),
402       };
403
404       if ( $signup_info_cache_agent->{'agent-ship_address'} 
405            && $agent->agent_cust_main ) {
406
407         my $cust_main = $agent->agent_cust_main;
408         my $location = $cust_main->ship_location;
409         $signup_info_cache_agent->{"ship_$_"} = $location->get($_)
410           foreach qw( address1 city county state zip country );
411
412       }
413
414       $cache->set("signup_info_cache_agent$agentnum", $signup_info_cache_agent);
415
416     }
417
418     $signup_info->{$_} = $signup_info_cache_agent->{$_}
419       foreach keys %$signup_info_cache_agent;
420
421   }
422   # else {
423   # delete $signup_info->{'part_pkg'};
424   #}
425
426   warn "$me sorting package list\n" if $DEBUG > 1;
427   $signup_info->{'part_pkg'} = [ sort { $a->{pkg} cmp $b->{pkg} }  # case?
428                                       @{ $signup_info->{'part_pkg'} }
429                                ];
430   warn "$me done sorting package list\n" if $DEBUG > 1;
431
432   if ( exists $packet->{'session_id'} ) {
433     my $agent_signup_info = { %$signup_info };
434     delete $agent_signup_info->{agentnum2part_pkg};
435     $agent_signup_info->{'agent'} = $session->{'agent'};
436     return $agent_signup_info;
437   } 
438   elsif ( exists $packet->{'keys'} ) {
439     my @keys = @{ $packet->{'keys'} };
440     return { map { $_ => $signup_info->{$_} } @keys };
441   }
442   else {
443     return $signup_info;
444   }
445
446 }
447
448 sub domain_select_hash {
449   my $packet = shift;
450
451   my $response = {};
452
453   if ($packet->{pkgpart}) {
454     my $part_pkg = qsearchs('part_pkg' => { 'pkgpart' => $packet->{pkgpart} } );
455     #$packet->{svcpart} = $part_pkg->svcpart('svc_acct')
456     $packet->{svcpart} = $part_pkg->svcpart
457       if $part_pkg;
458   }
459
460   if ($packet->{svcpart}) {
461     my $part_svc = qsearchs('part_svc' => { 'svcpart' => $packet->{svcpart} } );
462     $response->{'domsvc'} = $part_svc->part_svc_column('domsvc')->columnvalue
463       if ($part_svc && $part_svc->part_svc_column('domsvc')->columnflag  eq 'D');
464   }
465
466   $response->{'domains'}
467     = { domain_select_hash FS::svc_acct( map { $_ => $packet->{$_} }
468                                                  qw(svcpart pkgnum)
469                                        ) };
470
471   $response;
472 }
473
474 sub new_customer {
475   my $packet = shift;
476
477   my $conf = new FS::Conf;
478   my $svc_x = $conf->config('signup_server-service') || 'svc_acct';
479
480   if ( $svc_x eq 'svc_acct' ) {
481   
482     #things that aren't necessary in base class, but are for signup server
483       #return "Passwords don't match"
484       #  if $hashref->{'_password'} ne $hashref->{'_password2'}
485     return { 'error' => gettext('empty_password') }
486       unless length($packet->{'_password'});
487     # a bit inefficient for large numbers of pops
488     return { 'error' => gettext('no_access_number_selected') }
489       unless $packet->{'popnum'} || !scalar(qsearch('svc_acct_pop',{} ));
490
491   }
492   elsif ( $svc_x eq 'svc_pbx' ) {
493     #possibly some validation will be needed
494   }
495
496   my $agentnum;
497   if ( exists $packet->{'session_id'} ) {
498     my $cache = new FS::ClientAPI_SessionCache( {
499       'namespace' => 'FS::ClientAPI::Agent',
500     } );
501     my $session = $cache->get($packet->{'session_id'});
502     if ( $session ) {
503       $agentnum = $session->{'agentnum'};
504     } else {
505       return { 'error' => "Can't resume session" }; #better error message
506     }
507   } else {
508     $agentnum = $packet->{agentnum}
509                 || $conf->config('signup_server-default_agentnum');
510   }
511
512   my ($bill_hash, $ship_hash);
513   foreach my $f (FS::cust_main->location_fields) {
514     # avoid having to change this in front-end code
515     $bill_hash->{$f} = $packet->{"bill_$f"} || $packet->{$f};
516     $ship_hash->{$f} = $packet->{"ship_$f"};
517   }
518
519   #shares some stuff with htdocs/edit/process/cust_main.cgi... take any
520   # common that are still here and library them.
521   my $template_custnum = $conf->config('signup_server-prepaid-template-custnum');
522   my $cust_main;
523   if ( $template_custnum && $packet->{prepaid_shortform} ) {
524
525     my $template_cust = qsearchs('cust_main', { 'custnum' => $template_custnum } );
526     return { 'error' => 'Configuration error' } unless $template_cust;
527     #XXX Copy template customer's locations
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 address1 address2 
535               city county state zip country
536               daytime night fax 
537
538               ship_last ship_first ship_company ship_address1 ship_address2
539               ship_city ship_county ship_state ship_zip ship_country
540               ship_daytime ship_night ship_fax
541             )
542       ),
543
544       ( map { $_ => $packet->{$_} } qw(
545               ss stateid stateid_state
546
547               payby
548               payinfo paycvv paydate payname paystate paytype
549               paystart_month paystart_year payissue
550               payip
551
552               referral_custnum comments
553             )
554       ),
555
556     } );
557
558   } else {
559
560     $cust_main = new FS::cust_main ( {
561       #'custnum'          => '',
562       'agentnum'      => $agentnum,
563       'refnum'        => $packet->{refnum}
564                          || $conf->config('signup_server-default_refnum'),
565
566       map { $_ => $packet->{$_} } qw(
567         last first ss company 
568         daytime night fax stateid stateid_state
569         payby
570         payinfo paycvv paydate payname paystate paytype
571         paystart_month paystart_year payissue
572         payip
573         override_ban_warn
574         referral_custnum comments
575       ),
576
577     } );
578   }
579
580   my $bill_location = FS::cust_location->new($bill_hash);
581   my $ship_location;
582   my $agent = qsearchs('agent', { 'agentnum' => $agentnum } );
583   if ( $conf->exists('agent-ship_address', $agentnum) 
584     && $agent->agent_custnum ) {
585
586     my $agent_cust_main = $agent->agent_cust_main;
587     my $prefix = length($agent_cust_main->ship_last) ? 'ship_' : '';
588     $ship_location = FS::cust_location->new({ 
589         $agent_cust_main->ship_location->location_hash
590     });
591
592   }
593   # we don't have an equivalent of the "same" checkbox in selfservice
594   # so is there a ship address, and if so, is it different from the billing 
595   # address?
596   elsif ( length($ship_hash->{address1}) > 0 and
597           grep { $bill_hash->{$_} ne $ship_hash->{$_} } keys(%$ship_hash)
598          ) {
599
600     $ship_location = FS::cust_location->new( $ship_hash );
601   
602   }
603   else {
604     $ship_location = $bill_location;
605   }
606
607   $cust_main->set('bill_location' => $bill_location);
608   $cust_main->set('ship_location' => $ship_location);
609
610   return { 'error' => "Illegal payment type" }
611     unless grep { $_ eq $packet->{'payby'} }
612                 $conf->config('signup_server-payby');
613
614   if (FS::payby->realtime($packet->{payby})
615     and not $conf->exists('signup_server-third_party_as_card')) {
616     my $payby = $packet->{payby};
617
618     my $agent = qsearchs('agent', { 'agentnum' => $agentnum });
619     return { 'error' => "Unknown reseller" }
620       unless $agent;
621
622     my $gw;
623     my $gatewaynum = $conf->config('selfservice-payment_gateway');
624     if ( $gatewaynum ) {
625       $gw = qsearchs('payment_gateway', { gatewaynum => $gatewaynum });
626       die "configured gatewaynum $gatewaynum not found!" if !$gw;
627     }
628     else {
629       $gw = $agent->payment_gateway( 'method'  => FS::payby->payby2bop($payby),
630                                      'nofatal' => 1,
631                                     );
632     }
633
634     $cust_main->payby('BILL')   # MCRD better?
635       if $gw && $gw->gateway_namespace eq 'Business::OnlineThirdPartyPayment';
636   }
637
638   $cust_main->payinfo($cust_main->daytime)
639     if $cust_main->payby eq 'LECB' && ! $cust_main->payinfo;
640
641   my @invoicing_list = $packet->{'invoicing_list'}
642                          ? split( /\s*\,\s*/, $packet->{'invoicing_list'} )
643                          : ();
644
645   $packet->{'pkgpart'} =~ /^(\d+)$/ or '' =~ /^()$/;
646   my $pkgpart = $1;
647   return { 'error' => 'Please select a package' } unless $pkgpart; #msgcat
648
649   my $part_pkg =
650     qsearchs( 'part_pkg', { 'pkgpart' => $pkgpart } )
651       or return { 'error' => "WARNING: unknown pkgpart: $pkgpart" };
652   my $svcpart = $part_pkg->svcpart($svc_x);
653
654   my $reg_code = '';
655   if ( $packet->{'reg_code'} ) {
656     $reg_code = qsearchs( 'reg_code', { 'code'     => $packet->{'reg_code'},
657                                         'agentnum' => $agentnum,             } )
658       or return { 'error' => 'Unknown registration code' };
659   }
660
661   my $cust_pkg = new FS::cust_pkg ( {
662     #later#'custnum' => $custnum,
663     'pkgpart'    => $packet->{'pkgpart'},
664     'promo_code' => $packet->{'promo_code'},
665     'reg_code'   => $packet->{'reg_code'},
666   } );
667   #my $error = $cust_pkg->check;
668   #return { 'error' => $error } if $error;
669
670   #should be all auto-magic and shit
671   my @svc = ();
672   if ( $svc_x eq 'svc_acct' ) {
673
674     my $svc = new FS::svc_acct {
675       'svcpart'   => $svcpart,
676       map { $_ => $packet->{$_} }
677         qw( username _password sec_phrase popnum ),
678     };
679
680     my @acct_snarf;
681     my $snarfnum = 1;
682     while (    exists($packet->{"snarf_machine$snarfnum"})
683             && length($packet->{"snarf_machine$snarfnum"}) ) {
684       my $acct_snarf = new FS::acct_snarf ( {
685         'machine'   => $packet->{"snarf_machine$snarfnum"},
686         'protocol'  => $packet->{"snarf_protocol$snarfnum"},
687         'username'  => $packet->{"snarf_username$snarfnum"},
688         '_password' => $packet->{"snarf_password$snarfnum"},
689       } );
690       $snarfnum++;
691       push @acct_snarf, $acct_snarf;
692     }
693     $svc->child_objects( \@acct_snarf );
694     push @svc, $svc;
695
696   } elsif ( $svc_x eq 'svc_phone' ) {
697
698     push @svc, new FS::svc_phone ( {
699       'svcpart' => $svcpart,
700        map { $_ => $packet->{$_} }
701          qw( countrycode phonenum sip_password pin ),
702     } );
703
704   } elsif ( $svc_x eq 'svc_pbx' ) {
705
706     push @svc, new FS::svc_pbx ( {
707         'svcpart' => $svcpart,
708         map { $_ => $packet->{$_} } 
709           qw( id title ),
710         } );
711   
712   } else {
713     die "unknown signup service $svc_x";
714   }
715
716   if ($packet->{'mac_addr'} && $conf->exists('signup_server-mac_addr_svcparts'))
717   {
718
719     my %mac_addr_svcparts = map { $_ => 1 }
720                             $conf->config('signup_server-mac_addr_svcparts');
721     my @pkg_svc = grep { $_->quantity && $mac_addr_svcparts{$_->svcpart} }
722                   $cust_pkg->part_pkg->pkg_svc;
723
724     return { 'error' => 'No service defined to assign mac address' }
725       unless @pkg_svc;
726
727     my $svc = new FS::svc_acct {
728       'svcpart'   => $pkg_svc[0]->svcpart, #multiple matches? alas..
729       'username'  => $packet->{'mac_addr'},
730       '_password' => '', #blank as requested (set passwordmin to 0)
731     };
732
733     push @svc, $svc;
734
735   }
736
737   foreach my $svc ( @svc ) {
738     my $y = $svc->setdefault; # arguably should be in new method
739     return { 'error' => $y } if $y && !ref($y);
740     #$error = $svc->check;
741     #return { 'error' => $error } if $error;
742   }
743
744   #setup a job dependancy to delay provisioning
745   my $placeholder = new FS::queue ( {
746     'job'    => 'FS::ClientAPI::Signup::__placeholder',
747     'status' => 'locked',
748   } );
749   my $error = $placeholder->insert;
750   return { 'error' => $error } if $error;
751
752   use Tie::RefHash;
753   tie my %hash, 'Tie::RefHash';
754   %hash = ( $cust_pkg => \@svc );
755   #msgcat
756   $error = $cust_main->insert(
757     \%hash,
758     \@invoicing_list,
759     'depend_jobnum' => $placeholder->jobnum,
760   );
761   if ( $error ) {
762     my $perror = $placeholder->delete;
763     $error .= " (Additionally, error removing placeholder: $perror)" if $perror;
764     return { 'error' => $error };
765   }
766
767   if ( $conf->exists('signup_server-realtime') ) {
768
769     #warn "$me Billing customer...\n" if $Debug;
770
771     my $bill_error = $cust_main->bill( 'depend_jobnum'=>$placeholder->jobnum );
772     #warn "$me error billing new customer: $bill_error"
773     #  if $bill_error;
774
775     $bill_error = $cust_main->apply_payments_and_credits;
776     #warn "$me error applying payments and credits for".
777     #     " new customer: $bill_error"
778     #  if $bill_error;
779
780     $bill_error = $cust_main->realtime_collect(
781        method        => FS::payby->payby2bop( $packet->{payby} ),
782        depend_jobnum => $placeholder->jobnum,
783        selfservice   => 1,
784     );
785     #warn "$me error collecting from new customer: $bill_error"
786     #  if $bill_error;
787
788     if ($bill_error && ref($bill_error) eq 'HASH') {
789       return { 'error' => '_collect',
790                ( map { $_ => $bill_error->{$_} }
791                  qw(popup_url reference collectitems)
792                ),
793                amount => $cust_main->balance,
794              };
795     }
796
797     $bill_error = $cust_main->apply_payments_and_credits;
798     #warn "$me error applying payments and credits for".
799     #     " new customer: $bill_error"
800     #  if $bill_error;
801
802     if ( $cust_main->balance > 0 ) {
803
804       #this makes sense.  credit is "un-doing" the invoice
805       $cust_main->credit( $cust_main->balance, 'signup server decline',
806                           'reason_type' => $conf->config('signup_credit_type'),
807                         );
808       $cust_main->apply_credits;
809
810       #should check list for errors...
811       #$cust_main->suspend;
812       local $FS::svc_Common::noexport_hack = 1;
813       $cust_main->cancel('quiet'=>1);
814
815       my $perror = $placeholder->depended_delete;
816       warn "error removing provisioning jobs after decline: $perror" if $perror;
817       unless ( $perror ) {
818         $perror = $placeholder->delete;
819         warn "error removing placeholder after decline: $perror" if $perror;
820       }
821
822       return { 'error' => '_decline' };
823     }
824
825   }
826
827   if ( $reg_code ) {
828     $error = $reg_code->delete;
829     return { 'error' => $error } if $error;
830   }
831
832   $error = $placeholder->delete;
833   return { 'error' => $error } if $error;
834
835   if ( $conf->exists('signup-duplicate_cc-warn_hours') ) {
836     my $hours = $conf->config('signup-duplicate_cc-warn_hours');
837     my $ban = new FS::banned_pay $cust_main->_new_banned_pay_hashref;
838     $ban->end_date( int( time + $hours*3600 ) );
839     $ban->bantype('warn');
840     $ban->reason('signup-duplicate_cc-warn_hours');
841     $error = $ban->insert;
842     warn "WARNING: error inserting temporary banned_pay for ".
843          " signup-duplicate_cc-warn_hours (proceeding anyway): $error"
844       if $error;
845   }
846
847   my %return = ( 'error'          => '',
848                  'signup_service' => $svc_x,
849                  'custnum'        => $cust_main->custnum,
850                );
851
852   if ( $svc[0] ) {
853
854     $return{'svcnum'} = $svc[0]->svcnum;
855
856     if ( $svc_x eq 'svc_acct' ) {
857       $return{$_} = $svc[0]->$_() for qw( username _password );
858     } elsif ( $svc_x eq 'svc_phone' ) {
859       $return{$_} = $svc[0]->$_() for qw(countrycode phonenum sip_password pin);
860     } elsif ( $svc_x eq 'svc_pbx' ) {
861       #$return{$_} = $svc[0]->$_() for qw( ) #nothing yet
862      } else {
863       return {'error' => "configuration error: unknown signup service $svc_x"};
864       #die "unknown signup service $svc_x";
865       # return an error that's visible to someone somewhere
866     }
867
868   }
869
870   return \%return;
871
872 }
873
874 sub capture_payment {
875   my $packet = shift;
876
877   warn "$me capture_payment called on $packet\n" if $DEBUG;
878
879   ###
880   # identify processor/gateway from called back URL
881   ###
882
883   my $conf = new FS::Conf;
884
885   my $payment_gateway;
886   if ( my $gwnum = $conf->config('selfservice-payment_gateway') ) {
887     $payment_gateway = qsearchs('payment_gateway', { 'gatewaynum' => $gwnum })
888       or die "configured gatewaynum $gwnum not found!";
889   }
890   else {
891     my $url = $packet->{url};
892
893     $payment_gateway = qsearchs('payment_gateway', 
894         { 'gateway_callback_url' => popurl(0, $url) } 
895       );
896     if (!$payment_gateway) { 
897
898       my ( $processor, $login, $password, $action, @bop_options ) =
899         $conf->config('business-onlinepayment');
900       $action ||= 'normal authorization';
901       pop @bop_options if scalar(@bop_options) % 2 && $bop_options[-1] =~ /^\s*$/;
902       die "No real-time processor is enabled - ".
903           "did you set the business-onlinepayment configuration value?\n"
904         unless $processor;
905
906       $payment_gateway = new FS::payment_gateway( {
907         gateway_namespace => $conf->config('business-onlinepayment-namespace'),
908         gateway_module    => $processor,
909         gateway_username  => $login,
910         gateway_password  => $password,
911         gateway_action    => $action,
912         options   => [ ( @bop_options ) ],
913       });
914     }
915   }
916  
917   die "No real-time third party processor is enabled - ".
918       "did you set the business-onlinepayment configuration value?\n*"
919     unless $payment_gateway->gateway_namespace eq 'Business::OnlineThirdPartyPayment';
920
921   ###
922   # locate pending transaction
923   ###
924
925   eval "use Business::OnlineThirdPartyPayment";
926   die $@ if $@;
927
928   my $transaction =
929     new Business::OnlineThirdPartyPayment( $payment_gateway->gateway_module,
930                                            @{ [ $payment_gateway->options ] },
931                                          );
932
933   my $paypendingnum = $transaction->reference($packet->{data});
934
935   my $cust_pay_pending =
936     qsearchs('cust_pay_pending', { paypendingnum => $paypendingnum } );
937
938   unless ($cust_pay_pending) {
939     my $bill_error = "No payment is being processed with id $paypendingnum".
940                      "; Transaction aborted.";
941     return { error => '_decline', bill_error => $bill_error };
942   }
943
944   if ($cust_pay_pending->status ne 'thirdparty') {
945     my $bill_error = "Payment with id $paypendingnum is not thirdparty, but ".
946                      $cust_pay_pending->status.  "; Transaction aborted.";
947     return { error => '_decline', bill_error => $bill_error };
948   }
949
950   my $cust_main = $cust_pay_pending->cust_main;
951   my $bill_error =
952     $cust_main->realtime_botpp_capture( $cust_pay_pending, 
953       %{$packet->{data}},
954       apply => 1,
955   );
956
957   return { 'error'      => ( $bill_error->{bill_error} ? '_decline' : '' ),
958            %$bill_error,
959          };
960
961 }
962
963 1;