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 subs qw( _myaccount_cache );
6 use Data::Dumper;
7 use Tie::RefHash;
8 use Digest::SHA qw(sha512_hex);
9 use FS::Conf;
10 use FS::Record qw(qsearch qsearchs dbdef);
11 use FS::CGI qw(popurl);
12 use FS::Msgcat qw(gettext);
13 use FS::Misc qw(card_types);
14 use FS::ClientAPI_SessionCache;
15 use FS::agent;
16 use FS::cust_main_county;
17 use FS::part_pkg;
18 use FS::svc_acct_pop;
19 use FS::cust_main;
20 use FS::cust_pkg;
21 use FS::svc_acct;
22 use FS::svc_phone;
23 use FS::acct_snarf;
24 use FS::queue;
25 use FS::reg_code;
26 use FS::payby;
27 use FS::banned_pay;
28 use FS::part_tag;
29 use FS::cust_payby;
30
31 $DEBUG = 1;
32 $me = '[FS::ClientAPI::Signup]';
33
34 sub clear_cache {
35   warn "$me clear_cache called\n" if $DEBUG;
36   my $cache = new FS::ClientAPI_SessionCache( {
37       'namespace' => 'FS::ClientAPI::Signup',
38   } );
39   $cache->clear();
40   return {};
41 }
42
43 sub signup_info {
44   my $packet = shift;
45
46   warn "$me signup_info called on $packet\n" if $DEBUG;
47
48   my $conf = new FS::Conf;
49   my $svc_x = $conf->config('signup_server-service') || 'svc_acct';
50
51   my $cache = new FS::ClientAPI_SessionCache( {
52     'namespace' => 'FS::ClientAPI::Signup',
53   } );
54   my $signup_info_cache = $cache->get('signup_info_cache');
55
56   if ( $signup_info_cache ) {
57
58     warn "$me loading cached signup info\n" if $DEBUG > 1;
59
60   } else {
61
62     warn "$me populating signup info cache\n" if $DEBUG > 1;
63
64     my $agentnum2part_pkg = 
65       {
66         map {
67           my $agent = $_;
68           my $href = $agent->pkgpart_hashref;
69           $agent->agentnum =>
70             [
71               map { { 'payby'       => [ $_->payby ],
72                       'freq_pretty' => $_->freq_pretty,
73                       'options'     => { $_->options },
74                       %{$_->hashref}
75                   } }
76                 grep { $_->svcpart($svc_x)
77                        && ( $href->{ $_->pkgpart }
78                             || ( $_->agentnum
79                                  && $_->agentnum == $agent->agentnum
80                                )
81                           )
82                      }
83                   qsearch( 'part_pkg', { 'disabled' => '' } )
84             ];
85         } qsearch('agent', { 'disabled' => '' })
86       };
87
88     my $msgcat = { map { $_=>gettext($_) }
89                        qw( passwords_dont_match invalid_card unknown_card_type
90                            not_a empty_password illegal_or_empty_text )
91                  };
92     warn "msgcat: ". Dumper($msgcat). "\n" if $DEBUG > 2;
93
94     my $label = { map { $_ => FS::Msgcat::_gettext($_) }
95                       qw( stateid stateid_state )
96                 };
97     warn "label: ". Dumper($label). "\n" if $DEBUG > 2;
98
99     my @agent_fields = qw( agentnum agent );
100
101     my @bools = qw( emailinvoiceonly security_phrase );
102
103     my @signup_bools = qw( no_company recommend_daytime recommend_email );
104
105     my @signup_server_scalars = qw( default_pkgpart default_svcpart default_domsvc );
106
107     my @selfservice_textareas = qw( head body_header body_footer );
108
109     my @selfservice_scalars = qw(
110       body_bgcolor box_bgcolor
111       text_color link_color vlink_color hlink_color alink_color
112       font title_color title_align title_size menu_bgcolor menu_fontsize
113     );
114
115     #XXX my @selfservice_bools = qw(
116     #  menu_skipblanks menu_skipheadings menu_nounderline
117     #);
118
119     #my $selfservice_binaries = qw(
120     #  title_left_image title_right_image
121     #  menu_top_image menu_body_image menu_bottom_image
122     #);
123
124     $signup_info_cache = {
125
126       'cust_main_county' => [ map $_->hashref,
127                                   qsearch('cust_main_county', {} )
128                             ],
129
130       'agent' => [ map { my $agent = $_;
131                          +{ map { $_ => $agent->get($_) } @agent_fields }
132                        }
133                        qsearch('agent', { 'disabled' => '' } )
134                  ],
135
136       'part_referral' => [ map $_->hashref,
137                                qsearch('part_referral', { 'disabled' => '' } )
138                          ],
139
140       'agentnum2part_pkg' => $agentnum2part_pkg,
141
142       'svc_acct_pop' => [ map $_->hashref, qsearch('svc_acct_pop',{} ) ],
143
144       'emailinvoiceonly' => $conf->exists('emailinvoiceonly'),
145
146       'security_phrase' => $conf->exists('security_phrase'),
147
148       'nomadix' => $conf->exists('signup_server-nomadix'),
149
150       'payby' => [ $conf->config('signup_server-payby') ],
151
152       'payby_longname' => [ map { FS::payby->longname($_) } 
153                             $conf->config('signup_server-payby') ],
154
155       'card_types' => card_types(),
156
157       ( map { $_ => $conf->exists("signup-$_") } @signup_bools ),
158
159       ( map { $_ => scalar($conf->config("signup_server-$_")) }
160             @signup_server_scalars
161       ),
162
163       ( map { $_ => join("\n", $conf->config("selfservice-$_")) }
164             @selfservice_textareas
165       ),
166       ( map { $_ => scalar($conf->config("selfservice-$_")) }
167             @selfservice_scalars
168       ),
169
170       #( map { $_ => scalar($conf->config_binary("selfservice-$_")) }
171       #      @selfservice_binaries
172       #),
173
174       'agentnum2part_pkg'  => $agentnum2part_pkg,
175       'svc_acct_pop'       => [ map $_->hashref, qsearch('svc_acct_pop',{} ) ],
176       'nomadix'            => $conf->exists('signup_server-nomadix'),
177       'payby'              => [ $conf->config('signup_server-payby') ],
178       'card_types'         => card_types(),
179       'paytypes'           => [ FS::cust_payby->paytypes ],
180       'cvv_enabled'        => 1,
181       'require_cvv'        => $conf->exists('signup-require_cvv'),
182       'stateid_enabled'    => $conf->exists('show_stateid'),
183       'paystate_enabled'   => $conf->exists('show_bankstate'),
184       'exempt_groups'      => [ grep /\S/, $conf->config('tax-cust_exempt-groups') ],
185       'ship_enabled'       => 1,
186       'msgcat'             => $msgcat,
187       'label'              => $label,
188       'statedefault'       => scalar($conf->config('statedefault')) || 'CA',
189       'countrydefault'     => scalar($conf->config('countrydefault')) || 'US',
190       'refnum'             => scalar($conf->config('signup_server-default_refnum')),
191       'signup_service'     => $svc_x,
192       'company_name'       => scalar($conf->config('company_name')),
193       #per-agent?
194       'logo'               => scalar($conf->config_binary('logo.png')),
195       'prepaid_template_custnum' => $conf->exists('signup_server-prepaid-template-custnum'),
196     };
197
198     $cache->set('signup_info_cache', $signup_info_cache);
199
200   }
201
202   my $signup_info = { %$signup_info_cache };
203   warn "$me signup info loaded\n" if $DEBUG > 1;
204   warn Dumper($signup_info). "\n" if $DEBUG > 2;
205
206   my @addl = qw( signup_server-classnum2 signup_server-classnum3 );
207
208   if ( grep { $conf->exists($_) } @addl ) {
209   
210     $signup_info->{optional_packages} = [];
211
212     foreach my $addl ( @addl ) {
213
214       warn "$me adding optional package info\n" if $DEBUG > 1;
215
216       my $classnum = $conf->config($addl) or next;
217
218       my @pkgs = map { {
219                          'freq_pretty' => $_->freq_pretty,
220                          'options'     => { $_->options },
221                          %{ $_->hashref }
222                        };
223                      }
224                      qsearch( 'part_pkg', { classnum => $classnum } );
225
226       push @{$signup_info->{optional_packages}}, \@pkgs;
227
228       warn "$me done adding opt. package info for $classnum\n" if $DEBUG > 1;
229
230     }
231
232   }
233
234   my $agentnum = $packet->{'agentnum'}
235                  || $conf->config('signup_server-default_agentnum');
236   $agentnum =~ /^(\d*)$/ or die "illegal agentnum";
237   $agentnum = $1;
238
239   my $session = '';
240   if ( exists $packet->{'session_id'} ) {
241
242     warn "$me loading agent session\n" if $DEBUG > 1;
243     my $cache = new FS::ClientAPI_SessionCache( {
244       'namespace' => 'FS::ClientAPI::Agent',
245     } );
246     $session = $cache->get($packet->{'session_id'});
247     if ( $session ) {
248       $agentnum = $session->{'agentnum'};
249     } else {
250       return { 'error' => "Can't resume session" }; #better error message
251     }
252     warn "$me done loading agent session\n" if $DEBUG > 1;
253
254   } elsif ( exists $packet->{'customer_session_id'} ) {
255
256     warn "$me loading customer session\n" if $DEBUG > 1;
257     my $cache = new FS::ClientAPI_SessionCache( {
258       'namespace' => 'FS::ClientAPI::MyAccount',
259     } );
260     $session = $cache->get($packet->{'customer_session_id'});
261     if ( $session ) {
262       my $custnum = $session->{'custnum'};
263       my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum });
264       return { 'error' => "Can't find your customer record" } unless $cust_main;
265       $agentnum = $cust_main->agentnum;
266     } else {
267       return { 'error' => "Can't resume session" }; #better error message
268     }
269     warn "$me done loading customer session\n" if $DEBUG > 1;
270
271   }
272
273   $signup_info->{'part_pkg'} = [];
274
275   if ( $packet->{'reg_code'} ) {
276
277     warn "$me setting package list via reg_code\n" if $DEBUG > 1;
278
279     $signup_info->{'part_pkg'} = 
280       [ map { { 'payby'       => [ $_->payby ],
281                 'freq_pretty' => $_->freq_pretty,
282                 'options'     => { $_->options },
283                 %{$_->hashref}
284               };
285             }
286           grep { $_->svcpart($svc_x) }
287           map { $_->part_pkg }
288             qsearchs( 'reg_code', { 'code'     => $packet->{'reg_code'},
289                                     'agentnum' => $agentnum,              } )
290
291       ];
292
293     $signup_info->{'error'} = 'Unknown registration code'
294       unless @{ $signup_info->{'part_pkg'} };
295
296     warn "$me done setting package list via reg_code\n" if $DEBUG > 1;
297
298   } elsif ( $packet->{'promo_code'} ) {
299
300     warn "$me setting package list via promo_code\n" if $DEBUG > 1;
301
302     $signup_info->{'part_pkg'} =
303       [ map { { 'payby'   => [ $_->payby ],
304                 'freq_pretty' => $_->freq_pretty,
305                 'options'     => { $_->options },
306                 %{$_->hashref}
307             } }
308           grep { $_->svcpart($svc_x) }
309             qsearch( 'part_pkg', { 'promo_code' => {
310                                      op=>'ILIKE',
311                                      value=>$packet->{'promo_code'}
312                                    },
313                                    'disabled'   => '',                  } )
314       ];
315
316     $signup_info->{'error'} = 'Unknown promotional code'
317       unless @{ $signup_info->{'part_pkg'} };
318
319     warn "$me done setting package list via promo_code\n" if $DEBUG > 1;
320   }
321
322   if ( $agentnum ) {
323
324     warn "$me setting agent-specific payment flag\n" if $DEBUG > 1;
325     my $agent = qsearchs('agent', { 'agentnum' => $agentnum } )
326       or return { 'error' => "Self-service agent #$agentnum does not exist" };
327     warn "$me has agent $agent\n" if $DEBUG > 1;
328     my @paybys = @{ $signup_info->{'payby'} };
329     $signup_info->{'hide_payment_fields'} = [];
330
331     my $gatewaynum = $conf->config('selfservice-payment_gateway');
332     my $force_gateway;
333     if ( $gatewaynum ) {
334       $force_gateway = qsearchs('payment_gateway', { gatewaynum => $gatewaynum });
335       warn "using forced gateway #$gatewaynum - " .
336         $force_gateway->gateway_username . '@' . $force_gateway->gateway_module
337         if $DEBUG > 1;
338       die "configured gatewaynum $gatewaynum not found!" if !$force_gateway;
339     }
340     foreach my $payby (@paybys) {
341       warn "$me checking $payby payment fields\n" if $DEBUG > 1;
342       my $hide = 0;
343       if ( FS::payby->realtime($payby) ) {
344         my $gateway = $force_gateway || 
345           $agent->payment_gateway( 'method'  => FS::payby->payby2bop($payby),
346                                    'nofatal' => 1,
347                                  );
348         if ( $gateway && $gateway->gateway_namespace
349                     eq 'Business::OnlineThirdPartyPayment'
350            ) {
351           warn "$me hiding $payby payment fields\n" if $DEBUG > 1;
352           $hide = 1;
353         }
354       }
355       push @{$signup_info->{'hide_payment_fields'}}, $hide;
356     } # foreach $payby
357     warn "$me done setting agent-specific payment flag\n" if $DEBUG > 1;
358
359     warn "$me setting agent-specific package list\n" if $DEBUG > 1;
360     $signup_info->{'part_pkg'} = $signup_info->{'agentnum2part_pkg'}{$agentnum}
361       unless @{ $signup_info->{'part_pkg'} };
362     warn "$me done setting agent-specific package list\n" if $DEBUG > 1;
363
364     warn "$me setting agent-specific adv. source list\n" if $DEBUG > 1;
365     $signup_info->{'part_referral'} =
366       [
367         map { $_->hashref }
368           qsearch( {
369                      'table'     => 'part_referral',
370                      'hashref'   => { 'disabled' => '' },
371                      'extra_sql' => "AND (    agentnum = $agentnum  ".
372                                     "      OR agentnum IS NULL    ) ",
373                    },
374                  )
375       ];
376     warn "$me done setting agent-specific adv. source list\n" if $DEBUG > 1;
377
378     $signup_info->{'agent_name'} = $agent->agent;
379
380     $signup_info->{'company_name'} = $conf->config('company_name', $agentnum);
381
382     #some of the above could probably be cached, too
383
384     my $signup_info_cache_agent = $cache->get("signup_info_cache_agent$agentnum");
385
386     if ( $signup_info_cache_agent ) {
387
388       warn "$me loading cached signup info for agentnum $agentnum\n"
389         if $DEBUG > 1;
390
391     } else {
392
393       warn "$me populating signup info cache for agentnum $agentnum\n"
394         if $DEBUG > 1;
395
396       $signup_info_cache_agent = {
397         #( map { $_ => scalar( $conf->config($_, $agentnum) ) }
398         #  qw( company_name ) ),
399         ( map { $_ => scalar( $conf->config("selfservice-$_", $agentnum ) ) }
400           qw( body_bgcolor box_bgcolor menu_bgcolor ) ),
401         ( map { $_ => join("\n", $conf->config("selfservice-$_", $agentnum ) ) }
402           qw( head body_header body_footer ) ),
403         ( map { $_ => join("\n", $conf->config("signup_server-$_", $agentnum ) ) }
404           qw( terms_of_service ) ),
405
406         ( map { $_ => scalar($conf->exists($_, $agentnum)) } 
407           qw(cust_main-require_phone agent-ship_address) ),
408       };
409
410       if ( $signup_info_cache_agent->{'agent-ship_address'} 
411            && $agent->agent_cust_main ) {
412
413         my $cust_main = $agent->agent_cust_main;
414         my $location = $cust_main->ship_location;
415         $signup_info_cache_agent->{"ship_$_"} = $location->get($_)
416           foreach qw( address1 city county state zip country );
417
418       }
419
420       $cache->set("signup_info_cache_agent$agentnum", $signup_info_cache_agent);
421
422     }
423
424     $signup_info->{$_} = $signup_info_cache_agent->{$_}
425       foreach keys %$signup_info_cache_agent;
426
427   }
428   # else {
429   # delete $signup_info->{'part_pkg'};
430   #}
431
432   warn "$me sorting package list\n" if $DEBUG > 1;
433   $signup_info->{'part_pkg'} = [ sort { $a->{pkg} cmp $b->{pkg} }  # case?
434                                       @{ $signup_info->{'part_pkg'} }
435                                ];
436   warn "$me done sorting package list\n" if $DEBUG > 1;
437
438   if ( exists $packet->{'session_id'} ) {
439     my $agent_signup_info = { %$signup_info };
440     delete $agent_signup_info->{agentnum2part_pkg};
441     $agent_signup_info->{'agent'} = $session->{'agent'};
442     return $agent_signup_info;
443   } 
444   elsif ( exists $packet->{'keys'} ) {
445     my @keys = @{ $packet->{'keys'} };
446     return { map { $_ => $signup_info->{$_} } @keys };
447   }
448   else {
449     return $signup_info;
450   }
451
452 }
453
454 sub domain_select_hash {
455   my $packet = shift;
456
457   my $response = {};
458
459   if ($packet->{pkgpart}) {
460     my $part_pkg = qsearchs('part_pkg' => { 'pkgpart' => $packet->{pkgpart} } );
461     #$packet->{svcpart} = $part_pkg->svcpart('svc_acct')
462     $packet->{svcpart} = $part_pkg->svcpart
463       if $part_pkg;
464   }
465
466   if ($packet->{svcpart}) {
467     my $part_svc = qsearchs('part_svc' => { 'svcpart' => $packet->{svcpart} } );
468     $response->{'domsvc'} = $part_svc->part_svc_column('domsvc')->columnvalue
469       if ($part_svc && $part_svc->part_svc_column('domsvc')->columnflag  eq 'D');
470   }
471
472   $response->{'domains'}
473     = { domain_select_hash FS::svc_acct( map { $_ => $packet->{$_} }
474                                                  qw(svcpart pkgnum)
475                                        ) };
476
477   $response;
478 }
479
480 sub new_customer {
481   my $packet = shift;
482
483   my $conf = new FS::Conf;
484   my $svc_x = $conf->config('signup_server-service') || 'svc_acct';
485
486   if ( $svc_x eq 'svc_acct' ) {
487   
488     #things that aren't necessary in base class, but are for signup server
489       #return "Passwords don't match"
490       #  if $hashref->{'_password'} ne $hashref->{'_password2'}
491     return { 'error' => gettext('empty_password') }
492       unless length($packet->{'_password'});
493     # a bit inefficient for large numbers of pops
494     return { 'error' => gettext('no_access_number_selected') }
495       unless $packet->{'popnum'} || !scalar(qsearch('svc_acct_pop',{} ));
496
497   }
498   elsif ( $svc_x eq 'svc_pbx' ) {
499     #possibly some validation will be needed
500   }
501
502   my $agentnum;
503   if ( exists $packet->{'session_id'} ) {
504     my $cache = new FS::ClientAPI_SessionCache( {
505       'namespace' => 'FS::ClientAPI::Agent',
506     } );
507     my $session = $cache->get($packet->{'session_id'});
508     if ( $session ) {
509       $agentnum = $session->{'agentnum'};
510     } else {
511       return { 'error' => "Can't resume session" }; #better error message
512     }
513   } else {
514     $agentnum = $packet->{agentnum}
515                 || $conf->config('signup_server-default_agentnum');
516   }
517
518   my ($bill_hash, $ship_hash);
519   foreach my $f (FS::cust_main->location_fields) {
520     # avoid having to change this in front-end code
521     $bill_hash->{$f} = $packet->{"bill_$f"} || $packet->{$f};
522     $ship_hash->{$f} = $packet->{"ship_$f"};
523   }
524
525   #shares some stuff with htdocs/edit/process/cust_main.cgi... take any
526   # common that are still here and library them.
527
528   my %cust_main = (
529     'agentnum' => $agentnum,
530     'refnum'   => $packet->{refnum}
531                   || $conf->config('signup_server-default_refnum'),
532     'tagnum'   => [ FS::part_tag->default_tags ],
533
534     ( map { $_ => $packet->{$_} } qw(
535             salesnum
536             ss stateid stateid_state
537             locale
538             referral_custnum comments
539           )
540     ),
541
542   );
543
544   my %insert_options = ();
545   if ( $packet->{payby} =~ /^(CARD|DCRD|CHEK|DCHK)$/ ) {
546     $insert_options{cust_payby} = [
547       new FS::cust_payby {
548         map { $_ => $packet->{$_} } qw(
549           payby
550           payinfo paycvv paydate payname paystate paytype
551           paystart_month paystart_year payissue
552           payip
553         ),
554       }
555     ];
556   }
557
558   my $template_custnum = $conf->config('signup_server-prepaid-template-custnum');
559   my $cust_main;
560   if ( $template_custnum && $packet->{prepaid_shortform} ) {
561
562     my $template_cust = qsearchs('cust_main', { 'custnum' => $template_custnum } );
563     return { 'error' => 'Configuration error' } unless $template_cust;
564     $cust_main = new FS::cust_main ( {
565       %cust_main,
566       map { $_ => $template_cust->$_ } qw( 
567         last first company daytime night fax mobile
568       ),
569     } );
570
571     $bill_hash = { $template_cust->bill_location->location_hash };
572     $ship_hash = { $template_cust->ship_location->location_hash };
573
574   } else {
575
576     $cust_main = new FS::cust_main ( {
577       %cust_main,
578       map { $_ => $packet->{$_} } qw(
579         last first company daytime night fax mobile
580         override_ban_warn
581       ),
582     } );
583   }
584
585   my $bill_location = FS::cust_location->new($bill_hash);
586   my $ship_location;
587   my $agent = qsearchs('agent', { 'agentnum' => $agentnum } );
588   if ( $conf->exists('agent-ship_address', $agentnum) 
589     && $agent->agent_custnum ) {
590
591     my $agent_cust_main = $agent->agent_cust_main;
592     my $prefix = length($agent_cust_main->ship_last) ? 'ship_' : '';
593     $ship_location = FS::cust_location->new({ 
594         $agent_cust_main->ship_location->location_hash
595     });
596
597   }
598   # we don't have an equivalent of the "same" checkbox in selfservice
599   # so is there a ship address, and if so, is it different from the billing 
600   # address?
601   elsif ( length($ship_hash->{address1}) > 0 and
602           grep { $bill_hash->{$_} ne $ship_hash->{$_} } keys(%$ship_hash)
603          ) {
604
605     $ship_location = FS::cust_location->new( $ship_hash );
606   
607   }
608   else {
609     $ship_location = $bill_location;
610   }
611
612   $cust_main->set('bill_location' => $bill_location);
613   $cust_main->set('ship_location' => $ship_location);
614
615   return { 'error' => "Illegal payment type" }
616     unless grep { $_ eq $packet->{'payby'} }
617                 $conf->config('signup_server-payby');
618
619   if (FS::payby->realtime($packet->{payby})
620     and not $conf->exists('signup_server-third_party_as_card')) {
621     my $payby = $packet->{payby};
622
623     my $agent = qsearchs('agent', { 'agentnum' => $agentnum });
624     return { 'error' => "Unknown reseller" }
625       unless $agent;
626
627     my $gw;
628     my $gatewaynum = $conf->config('selfservice-payment_gateway');
629     if ( $gatewaynum ) {
630       $gw = qsearchs('payment_gateway', { gatewaynum => $gatewaynum });
631       die "configured gatewaynum $gatewaynum not found!" if !$gw;
632     }
633     else {
634       $gw = $agent->payment_gateway( 'method'  => FS::payby->payby2bop($payby),
635                                      'nofatal' => 1,
636                                     );
637     }
638
639     $cust_main->payby('BILL')   # MCRD better?  no, that's for something else
640       if $gw && $gw->gateway_namespace eq 'Business::OnlineThirdPartyPayment';
641   }
642
643   return { 'error' => "CVV2 is required" }
644     if $cust_main->payby =~ /^(CARD|DCRD)$/
645     && ! $cust_main->paycvv
646     && $conf->exists('signup-require_cvv');
647
648   $cust_main->payinfo($cust_main->daytime)
649     if $cust_main->payby eq 'LECB' && ! $cust_main->payinfo;
650
651   my @invoicing_list = $packet->{'invoicing_list'}
652                          ? split( /\s*\,\s*/, $packet->{'invoicing_list'} )
653                          : ();
654
655   my @exempt_groups = grep /\S/, $conf->config('tax-cust_exempt-groups');
656   my @tax_exempt = grep { $packet->{"tax_$_"} eq 'Y' } @exempt_groups;
657   $insert_options{'tax_exemption'} = {
658     map { $_ => $packet->{"tax_$_".'_num'} } @tax_exempt
659   };
660
661   $packet->{'pkgpart'} =~ /^(\d+)$/ or '' =~ /^()$/;
662   my $pkgpart = $1;
663   return { 'error' => 'Please select a package' } unless $pkgpart; #msgcat
664
665   my $part_pkg =
666     qsearchs( 'part_pkg', { 'pkgpart' => $pkgpart } )
667       or return { 'error' => "WARNING: unknown pkgpart: $pkgpart" };
668
669   my $reg_code = '';
670   if ( $packet->{'reg_code'} ) {
671     $reg_code = qsearchs( 'reg_code', { 'code'     => $packet->{'reg_code'},
672                                         'agentnum' => $agentnum,             } )
673       or return { 'error' => 'Unknown registration code' };
674   }
675
676   my $cust_pkg = new FS::cust_pkg ( {
677     #later#'custnum' => $custnum,
678     'pkgpart'    => $packet->{'pkgpart'},
679     'promo_code' => $packet->{'promo_code'},
680     'reg_code'   => $packet->{'reg_code'},
681   } );
682   #my $error = $cust_pkg->check;
683   #return { 'error' => $error } if $error;
684
685   my @svc = ();
686   unless ( $svc_x eq 'none' ) {
687
688     my $svcpart = $part_pkg->svcpart($svc_x);
689     #should be all auto-magic and shit
690     if ( $svc_x eq 'svc_acct' ) {
691
692       my $svc = new FS::svc_acct {
693         'svcpart'   => $svcpart,
694         map { $_ => $packet->{$_} }
695           qw( username _password sec_phrase popnum domsvc ),
696       };
697
698       my @acct_snarf;
699       my $snarfnum = 1;
700       while (    exists($packet->{"snarf_machine$snarfnum"})
701               && length($packet->{"snarf_machine$snarfnum"}) ) {
702         my $acct_snarf = new FS::acct_snarf ( {
703           'machine'   => $packet->{"snarf_machine$snarfnum"},
704           'protocol'  => $packet->{"snarf_protocol$snarfnum"},
705           'username'  => $packet->{"snarf_username$snarfnum"},
706           '_password' => $packet->{"snarf_password$snarfnum"},
707         } );
708         $snarfnum++;
709         push @acct_snarf, $acct_snarf;
710       }
711       $svc->child_objects( \@acct_snarf );
712       push @svc, $svc;
713
714     } elsif ( $svc_x eq 'svc_phone' ) {
715
716       push @svc, new FS::svc_phone ( {
717         'svcpart' => $svcpart,
718          map { $_ => $packet->{$_} }
719            qw( countrycode phonenum sip_password pin ),
720       } );
721
722     } elsif ( $svc_x eq 'svc_pbx' ) {
723
724       push @svc, new FS::svc_pbx ( {
725           'svcpart' => $svcpart,
726           map { $_ => $packet->{$_} } 
727             qw( id title ),
728           } );
729   
730     } else {
731       die "unknown signup service $svc_x";
732     }
733
734   }
735
736   if ($packet->{'mac_addr'} && $conf->exists('signup_server-mac_addr_svcparts'))
737   {
738
739     my %mac_addr_svcparts = map { $_ => 1 }
740                             $conf->config('signup_server-mac_addr_svcparts');
741     my @pkg_svc = grep { $_->quantity && $mac_addr_svcparts{$_->svcpart} }
742                   $cust_pkg->part_pkg->pkg_svc;
743
744     return { 'error' => 'No service defined to assign mac address' }
745       unless @pkg_svc;
746
747     my $svc = new FS::svc_acct {
748       'svcpart'   => $pkg_svc[0]->svcpart, #multiple matches? alas..
749       'username'  => $packet->{'mac_addr'},
750       '_password' => '', #blank as requested (set passwordmin to 0)
751     };
752
753     push @svc, $svc;
754
755   }
756
757   foreach my $svc ( @svc ) {
758     my $y = $svc->setdefault; # arguably should be in new method
759     return { 'error' => $y } if $y && !ref($y);
760     #$error = $svc->check;
761     #return { 'error' => $error } if $error;
762   }
763
764   #setup a job dependancy to delay provisioning
765   my $placeholder = new FS::queue ( {
766     'job'    => 'FS::ClientAPI::Signup::__placeholder',
767     'status' => 'locked',
768   } );
769   my $error = $placeholder->insert;
770   return { 'error' => $error } if $error;
771
772   use Tie::RefHash;
773   tie my %hash, 'Tie::RefHash';
774   %hash = ( $cust_pkg => \@svc );
775   #msgcat
776   $error = $cust_main->insert(
777     \%hash,
778     \@invoicing_list,
779     'depend_jobnum' => $placeholder->jobnum,
780      %insert_options,
781   );
782   if ( $error ) {
783     my $perror = $placeholder->delete;
784     $error .= " (Additionally, error removing placeholder: $perror)" if $perror;
785     return { 'error' => $error };
786   }
787
788   if ( $conf->exists('signup_server-realtime') ) {
789
790     #warn "$me Billing customer...\n" if $Debug;
791
792     my @cust_bill;
793     my $bill_error = $cust_main->bill(
794       'depend_jobnum' => $placeholder->jobnum,
795       'return_bill'   => \@cust_bill,
796     );
797     #warn "$me error billing new customer: $bill_error"
798     #  if $bill_error;
799
800     $bill_error = $cust_main->apply_payments_and_credits;
801     #warn "$me error applying payments and credits for".
802     #     " new customer: $bill_error"
803     #  if $bill_error;
804
805     unless ( $packet->{payby} eq 'PREPAY' ) {
806       $bill_error = $cust_main->realtime_collect(
807          method        => FS::payby->payby2bop( $packet->{payby} ),
808          depend_jobnum => $placeholder->jobnum,
809          selfservice   => 1,
810       );
811       #warn "$me error collecting from new customer: $bill_error"
812       #  if $bill_error;
813     }
814
815     if ($bill_error && ref($bill_error) eq 'HASH') {
816       return { 'error' => '_collect',
817                ( map { $_ => $bill_error->{$_} }
818                  qw(popup_url reference collectitems)
819                ),
820                amount => $cust_main->balance,
821              };
822     }
823
824     $bill_error = $cust_main->apply_payments_and_credits;
825     #warn "$me error applying payments and credits for".
826     #     " new customer: $bill_error"
827     #  if $bill_error;
828
829     if ( $cust_main->balance > 0 ) {
830
831       #this used to apply a credit, but now we can void invoices...
832       foreach my $cust_bill (@cust_bill) {
833         my $voiderror = $cust_bill->void('automatic payment failed');
834         warn "Error voiding cust bill after decline: $voiderror" if $voiderror;
835       }
836
837       #should check list for errors...
838       #$cust_main->suspend;
839       local $FS::svc_Common::noexport_hack = 1;
840       $cust_main->cancel('quiet'=>1);
841
842       my $perror = $placeholder->depended_delete;
843       warn "error removing provisioning jobs after decline: $perror" if $perror;
844       unless ( $perror ) {
845         $perror = $placeholder->delete;
846         warn "error removing placeholder after decline: $perror" if $perror;
847       }
848
849       return { 'error' => '_decline' };
850     }
851
852   }
853
854   if ( $reg_code ) {
855     $error = $reg_code->delete;
856     return { 'error' => $error } if $error;
857   }
858
859   $error = $placeholder->delete;
860   return { 'error' => $error } if $error;
861
862   if ( $conf->exists('signup-duplicate_cc-warn_hours') ) {
863     my $hours = $conf->config('signup-duplicate_cc-warn_hours');
864     my $ban = new FS::banned_pay $cust_main->_new_banned_pay_hashref;
865     $ban->end_date( int( time + $hours*3600 ) );
866     $ban->bantype('warn');
867     $ban->reason('signup-duplicate_cc-warn_hours');
868     $error = $ban->insert;
869     warn "WARNING: error inserting temporary banned_pay for ".
870          " signup-duplicate_cc-warn_hours (proceeding anyway): $error"
871       if $error;
872   }
873
874   my %return = ( 'error'          => '',
875                  'signup_service' => $svc_x,
876                  'custnum'        => $cust_main->custnum,
877                );
878
879   if ( $svc[0] ) {
880
881     $return{'svcnum'} = $svc[0]->svcnum;
882
883     if ( $svc_x eq 'svc_acct' ) {
884       $return{$_} = $svc[0]->$_() for qw( username _password );
885     } elsif ( $svc_x eq 'svc_phone' ) {
886       $return{$_} = $svc[0]->$_() for qw(countrycode phonenum sip_password pin);
887     } elsif ( $svc_x eq 'svc_pbx' ) {
888       #$return{$_} = $svc[0]->$_() for qw( ) #nothing yet
889      } else {
890       return {'error' => "configuration error: unknown signup service $svc_x"};
891       #die "unknown signup service $svc_x";
892       # return an error that's visible to someone somewhere
893     }
894
895   }
896
897   return \%return;
898
899 }
900
901 #false laziness w/ above
902 # fresh restart to support "free account" portals with 3.x/4.x-style
903 #  addressless accounts
904 # and a contact (for self-service login)
905 sub new_customer_minimal {
906   my $packet = shift;
907
908   my $conf = new FS::Conf;
909   my $svc_x = $conf->config('signup_server-service') || 'svc_acct';
910
911   if ( $svc_x eq 'svc_acct' ) {
912   
913     #things that aren't necessary in base class, but are for signup server
914       #return "Passwords don't match"
915       #  if $hashref->{'_password'} ne $hashref->{'_password2'}
916     return { 'error' => gettext('empty_password') }
917       unless length($packet->{'_password'});
918     # a bit inefficient for large numbers of pops
919     return { 'error' => gettext('no_access_number_selected') }
920       unless $packet->{'popnum'} || !scalar(qsearch('svc_acct_pop',{} ));
921
922   }
923   elsif ( $svc_x eq 'svc_pbx' ) {
924     #possibly some validation will be needed
925   }
926
927   my $agentnum;
928   if ( exists $packet->{'session_id'} ) {
929     my $cache = new FS::ClientAPI_SessionCache( {
930       'namespace' => 'FS::ClientAPI::Agent',
931     } );
932     my $session = $cache->get($packet->{'session_id'});
933     if ( $session ) {
934       $agentnum = $session->{'agentnum'};
935     } else {
936       return { 'error' => "Can't resume session" }; #better error message
937     }
938   } else {
939     $agentnum = $packet->{agentnum}
940                 || $conf->config('signup_server-default_agentnum');
941   }
942
943   #shares some stuff with htdocs/edit/process/cust_main.cgi... take any
944   # common that are still here and library them.
945
946   my $cust_main = new FS::cust_main ( {
947       'agentnum' => $agentnum,
948       'refnum'   => $packet->{refnum}
949                     || $conf->config('signup_server-default_refnum'),
950       'tagnum'   => [ FS::part_tag->default_tags ],
951
952       map { $_ => $packet->{$_} } qw(
953         salesnum
954         last first company daytime night fax mobile
955         ss stateid stateid_state
956
957         locale
958       ),
959
960   } );
961
962   my %opt = ();
963   if ( $packet->{payby} =~ /^(CARD|DCRD|CHEK|DCHK)$/ ) {
964     $opt{cust_payby} = [
965       new FS::cust_payby {
966         map { $_ => $packet->{$_} } qw(
967           payby
968           payinfo paycvv paydate payname paystate paytype
969           paystart_month paystart_year payissue
970           payip
971         ),
972       }
973     ];
974   }
975
976   if ( grep length($packet->{$_}), FS::cust_main->location_fields ) {
977     my $bill_hash;
978     foreach my $f (FS::cust_main->location_fields) {
979       $bill_hash->{$f} =  $packet->{$f};
980     }
981     my $bill_location = FS::cust_location->new($bill_hash);
982     $cust_main->set('bill_location' => $bill_location);
983     $cust_main->set('ship_location' => $bill_location);
984   }
985
986   my @invoicing_list = $packet->{'invoicing_list'}
987                          ? split( /\s*\,\s*/, $packet->{'invoicing_list'} )
988                          : ();
989
990   use Tie::RefHash;
991   tie my %hash, 'Tie::RefHash', ();
992   my @svc = ();
993
994   $packet->{'pkgpart'} =~ /^(\d+)$/ or '' =~ /^()$/;
995   my $pkgpart = $1;
996
997   if ( $pkgpart ) {
998
999     my $part_pkg =
1000       qsearchs( 'part_pkg', { 'pkgpart' => $pkgpart } )
1001         or return { 'error' => "WARNING: unknown pkgpart: $pkgpart" };
1002
1003     my $cust_pkg = new FS::cust_pkg ( {
1004       #later#'custnum' => $custnum,
1005       'pkgpart'    => $packet->{'pkgpart'},
1006     } );
1007     #my $error = $cust_pkg->check;
1008     #return { 'error' => $error } if $error;
1009
1010     unless ( $svc_x eq 'none' ) {
1011
1012       my $svcpart = $part_pkg->svcpart($svc_x);
1013       #should be all auto-magic and shit
1014       if ( $svc_x eq 'svc_acct' ) {
1015
1016         my $svc = new FS::svc_acct {
1017           'svcpart'   => $svcpart,
1018           map { $_ => $packet->{$_} }
1019             qw( username _password sec_phrase popnum domsvc ),
1020         };
1021
1022         push @svc, $svc;
1023
1024       } elsif ( $svc_x eq 'svc_phone' ) {
1025
1026         push @svc, new FS::svc_phone ( {
1027           'svcpart' => $svcpart,
1028            map { $_ => $packet->{$_} }
1029              qw( countrycode phonenum sip_password pin ),
1030         } );
1031
1032       } elsif ( $svc_x eq 'svc_pbx' ) {
1033
1034         push @svc, new FS::svc_pbx ( {
1035             'svcpart' => $svcpart,
1036             map { $_ => $packet->{$_} } 
1037               qw( id title ),
1038             } );
1039     
1040       } else {
1041         die "unknown signup service $svc_x";
1042       }
1043
1044     }
1045
1046     foreach my $svc ( @svc ) {
1047       my $y = $svc->setdefault; # arguably should be in new method
1048       return { 'error' => $y } if $y && !ref($y);
1049       #$error = $svc->check;
1050       #return { 'error' => $error } if $error;
1051     }
1052
1053     use Tie::RefHash;
1054     tie my %hash, 'Tie::RefHash';
1055     $hash{ $cust_pkg } = \@svc;
1056
1057   }
1058
1059   if ( $invoicing_list[0] && $packet->{'_password'} ) {
1060     $opt{'contact'} = [
1061       new FS::contact { 'first'        => $cust_main->first,
1062                         'last'         => $cust_main->get('last'),
1063                         '_password'    => $packet->{'_password'},
1064                         'emailaddress' => $invoicing_list[0],
1065                         'selfservice_access' => 'Y',
1066                       }
1067     ];
1068   }
1069
1070   my $error = $cust_main->insert(
1071     \%hash,
1072     \@invoicing_list,
1073     %opt,
1074   );
1075   return { 'error' => $error } if $error;
1076
1077   my $session = { 'custnum' => $cust_main->custnum };
1078
1079   my $session_id;
1080   do {
1081     $session_id = sha512_hex(time(). {}. rand(). $$)
1082   } until ( ! defined _myaccount_cache->get($session_id) ); #just in case
1083
1084   _myaccount_cache->set( $session_id, $session, '1 hour' ); # 1 hour?
1085
1086   my %return = ( 'error'          => '',
1087                  'signup_service' => $svc_x,
1088                  'custnum'        => $cust_main->custnum,
1089                  'session_id'     => $session_id,
1090                  map { $_ => $cust_main->$_ } qw( first last company ),
1091                );
1092
1093   if ( $svc[0] ) {
1094
1095     $return{'svcnum'} = $svc[0]->svcnum;
1096
1097     if ( $svc_x eq 'svc_acct' ) {
1098       $return{$_} = $svc[0]->$_() for qw( username _password );
1099     } elsif ( $svc_x eq 'svc_phone' ) {
1100       $return{$_} = $svc[0]->$_() for qw(countrycode phonenum sip_password pin);
1101     } elsif ( $svc_x eq 'svc_pbx' ) {
1102       #$return{$_} = $svc[0]->$_() for qw( ) #nothing yet
1103      } else {
1104       return {'error' => "configuration error: unknown signup service $svc_x"};
1105       #die "unknown signup service $svc_x";
1106       # return an error that's visible to someone somewhere
1107     }
1108
1109   }
1110
1111   return \%return;
1112
1113 }
1114
1115 use vars qw( $myaccount_cache );
1116 sub _myaccount_cache {
1117   $myaccount_cache ||= new FS::ClientAPI_SessionCache( {
1118                          'namespace' => 'FS::ClientAPI::MyAccount',
1119                        } );
1120 }
1121
1122 sub capture_payment {
1123   my $packet = shift;
1124
1125   warn "$me capture_payment called on $packet\n" if $DEBUG;
1126
1127   ###
1128   # identify processor/gateway from called back URL
1129   ###
1130
1131   my $conf = new FS::Conf;
1132
1133   my $payment_gateway;
1134   if ( my $gwnum = $conf->config('selfservice-payment_gateway') ) {
1135     $payment_gateway = qsearchs('payment_gateway', { 'gatewaynum' => $gwnum })
1136       or die "configured gatewaynum $gwnum not found!";
1137   }
1138   else {
1139     my $url = $packet->{url};
1140
1141     $payment_gateway = qsearchs('payment_gateway', 
1142         { 'gateway_callback_url' => popurl(0, $url) } 
1143       );
1144     if (!$payment_gateway) { 
1145
1146       my ( $processor, $login, $password, $action, @bop_options ) =
1147         $conf->config('business-onlinepayment');
1148       $action ||= 'normal authorization';
1149       pop @bop_options if scalar(@bop_options) % 2 && $bop_options[-1] =~ /^\s*$/;
1150       die "No real-time processor is enabled - ".
1151           "did you set the business-onlinepayment configuration value?\n"
1152         unless $processor;
1153
1154       $payment_gateway = new FS::payment_gateway( {
1155         gateway_namespace => $conf->config('business-onlinepayment-namespace'),
1156         gateway_module    => $processor,
1157         gateway_username  => $login,
1158         gateway_password  => $password,
1159         gateway_action    => $action,
1160         options   => [ ( @bop_options ) ],
1161       });
1162     }
1163   }
1164  
1165   die "No real-time third party processor is enabled - ".
1166       "did you set the business-onlinepayment configuration value?\n*"
1167     unless $payment_gateway->gateway_namespace eq 'Business::OnlineThirdPartyPayment';
1168
1169   ###
1170   # locate pending transaction
1171   ###
1172
1173   eval "use Business::OnlineThirdPartyPayment";
1174   die $@ if $@;
1175
1176   my $transaction =
1177     new Business::OnlineThirdPartyPayment( $payment_gateway->gateway_module,
1178                                            @{ [ $payment_gateway->options ] },
1179                                          );
1180
1181   my $paypendingnum = $transaction->reference($packet->{data});
1182
1183   my $cust_pay_pending =
1184     qsearchs('cust_pay_pending', { paypendingnum => $paypendingnum } );
1185
1186   unless ($cust_pay_pending) {
1187     my $bill_error = "No payment is being processed with id $paypendingnum".
1188                      "; Transaction aborted.";
1189     return { error => '_decline', bill_error => $bill_error };
1190   }
1191
1192   if ($cust_pay_pending->status ne 'thirdparty') {
1193     my $bill_error = "Payment with id $paypendingnum is not thirdparty, but ".
1194                      $cust_pay_pending->status.  "; Transaction aborted.";
1195     return { error => '_decline', bill_error => $bill_error };
1196   }
1197
1198   my $cust_main = $cust_pay_pending->cust_main;
1199   if ( $packet->{cancel} ) {
1200     # the user has chosen not to make this payment
1201     # (probably should be a separate API call, but I don't want to duplicate
1202     # all of the above...which should eventually go away)
1203     my $error = $cust_pay_pending->delete;
1204     # don't show any errors related to this; they're not meaningful
1205     warn "error canceling pending payment $paypendingnum: $error\n" if $error;
1206     return { 'error'      => '_cancel',
1207              'session_id' => $cust_pay_pending->session_id };
1208   } else {
1209     # create the payment
1210     my $bill_error =
1211       $cust_main->realtime_botpp_capture( $cust_pay_pending, 
1212         %{$packet->{data}},
1213         apply => 1,
1214     );
1215
1216     return { 'error'      => ( $bill_error->{bill_error} ? '_decline' : '' ),
1217              %$bill_error,
1218            };
1219   }
1220
1221 }
1222
1223 1;