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