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