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