new_customer_minimal accepts address, & doc it, RT#34084
[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 = 1;
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   my @invoicing_list = $packet->{'invoicing_list'}
641                          ? split( /\s*\,\s*/, $packet->{'invoicing_list'} )
642                          : ();
643
644   my %insert_options = ();
645
646   my @exempt_groups = grep /\S/, $conf->config('tax-cust_exempt-groups');
647   my @tax_exempt = grep { $packet->{"tax_$_"} eq 'Y' } @exempt_groups;
648   $insert_options{'tax_exemption'} = {
649     map { $_ => $packet->{"tax_$_".'_num'} } @tax_exempt
650   };
651
652   $packet->{'pkgpart'} =~ /^(\d+)$/ or '' =~ /^()$/;
653   my $pkgpart = $1;
654   return { 'error' => 'Please select a package' } unless $pkgpart; #msgcat
655
656   my $part_pkg =
657     qsearchs( 'part_pkg', { 'pkgpart' => $pkgpart } )
658       or return { 'error' => "WARNING: unknown pkgpart: $pkgpart" };
659   my $svcpart = $part_pkg->svcpart($svc_x);
660
661   my $reg_code = '';
662   if ( $packet->{'reg_code'} ) {
663     $reg_code = qsearchs( 'reg_code', { 'code'     => $packet->{'reg_code'},
664                                         'agentnum' => $agentnum,             } )
665       or return { 'error' => 'Unknown registration code' };
666   }
667
668   my $cust_pkg = new FS::cust_pkg ( {
669     #later#'custnum' => $custnum,
670     'pkgpart'    => $packet->{'pkgpart'},
671     'promo_code' => $packet->{'promo_code'},
672     'reg_code'   => $packet->{'reg_code'},
673   } );
674   #my $error = $cust_pkg->check;
675   #return { 'error' => $error } if $error;
676
677   #should be all auto-magic and shit
678   my @svc = ();
679   if ( $svc_x eq 'svc_acct' ) {
680
681     my $svc = new FS::svc_acct {
682       'svcpart'   => $svcpart,
683       map { $_ => $packet->{$_} }
684         qw( username _password sec_phrase popnum domsvc ),
685     };
686
687     my @acct_snarf;
688     my $snarfnum = 1;
689     while (    exists($packet->{"snarf_machine$snarfnum"})
690             && length($packet->{"snarf_machine$snarfnum"}) ) {
691       my $acct_snarf = new FS::acct_snarf ( {
692         'machine'   => $packet->{"snarf_machine$snarfnum"},
693         'protocol'  => $packet->{"snarf_protocol$snarfnum"},
694         'username'  => $packet->{"snarf_username$snarfnum"},
695         '_password' => $packet->{"snarf_password$snarfnum"},
696       } );
697       $snarfnum++;
698       push @acct_snarf, $acct_snarf;
699     }
700     $svc->child_objects( \@acct_snarf );
701     push @svc, $svc;
702
703   } elsif ( $svc_x eq 'svc_phone' ) {
704
705     push @svc, new FS::svc_phone ( {
706       'svcpart' => $svcpart,
707        map { $_ => $packet->{$_} }
708          qw( countrycode phonenum sip_password pin ),
709     } );
710
711   } elsif ( $svc_x eq 'svc_pbx' ) {
712
713     push @svc, new FS::svc_pbx ( {
714         'svcpart' => $svcpart,
715         map { $_ => $packet->{$_} } 
716           qw( id title ),
717         } );
718   
719   } else {
720     die "unknown signup service $svc_x";
721   }
722
723   if ($packet->{'mac_addr'} && $conf->exists('signup_server-mac_addr_svcparts'))
724   {
725
726     my %mac_addr_svcparts = map { $_ => 1 }
727                             $conf->config('signup_server-mac_addr_svcparts');
728     my @pkg_svc = grep { $_->quantity && $mac_addr_svcparts{$_->svcpart} }
729                   $cust_pkg->part_pkg->pkg_svc;
730
731     return { 'error' => 'No service defined to assign mac address' }
732       unless @pkg_svc;
733
734     my $svc = new FS::svc_acct {
735       'svcpart'   => $pkg_svc[0]->svcpart, #multiple matches? alas..
736       'username'  => $packet->{'mac_addr'},
737       '_password' => '', #blank as requested (set passwordmin to 0)
738     };
739
740     push @svc, $svc;
741
742   }
743
744   foreach my $svc ( @svc ) {
745     my $y = $svc->setdefault; # arguably should be in new method
746     return { 'error' => $y } if $y && !ref($y);
747     #$error = $svc->check;
748     #return { 'error' => $error } if $error;
749   }
750
751   #setup a job dependancy to delay provisioning
752   my $placeholder = new FS::queue ( {
753     'job'    => 'FS::ClientAPI::Signup::__placeholder',
754     'status' => 'locked',
755   } );
756   my $error = $placeholder->insert;
757   return { 'error' => $error } if $error;
758
759   use Tie::RefHash;
760   tie my %hash, 'Tie::RefHash';
761   %hash = ( $cust_pkg => \@svc );
762   #msgcat
763   $error = $cust_main->insert(
764     \%hash,
765     \@invoicing_list,
766     'depend_jobnum' => $placeholder->jobnum,
767      %insert_options,
768   );
769   if ( $error ) {
770     my $perror = $placeholder->delete;
771     $error .= " (Additionally, error removing placeholder: $perror)" if $perror;
772     return { 'error' => $error };
773   }
774
775   if ( $conf->exists('signup_server-realtime') ) {
776
777     #warn "$me Billing customer...\n" if $Debug;
778
779     my $bill_error = $cust_main->bill( 'depend_jobnum'=>$placeholder->jobnum );
780     #warn "$me error billing new customer: $bill_error"
781     #  if $bill_error;
782
783     $bill_error = $cust_main->apply_payments_and_credits;
784     #warn "$me error applying payments and credits for".
785     #     " new customer: $bill_error"
786     #  if $bill_error;
787
788     unless ( $packet->{payby} eq 'PREPAY' ) {
789       $bill_error = $cust_main->realtime_collect(
790          method        => FS::payby->payby2bop( $packet->{payby} ),
791          depend_jobnum => $placeholder->jobnum,
792          selfservice   => 1,
793       );
794       #warn "$me error collecting from new customer: $bill_error"
795       #  if $bill_error;
796     }
797
798     if ($bill_error && ref($bill_error) eq 'HASH') {
799       return { 'error' => '_collect',
800                ( map { $_ => $bill_error->{$_} }
801                  qw(popup_url reference collectitems)
802                ),
803                amount => $cust_main->balance,
804              };
805     }
806
807     $bill_error = $cust_main->apply_payments_and_credits;
808     #warn "$me error applying payments and credits for".
809     #     " new customer: $bill_error"
810     #  if $bill_error;
811
812     if ( $cust_main->balance > 0 ) {
813
814       #this makes sense.  credit is "un-doing" the invoice
815       $cust_main->credit( $cust_main->balance, 'signup server decline',
816                           'reason_type' => $conf->config('signup_credit_type'),
817                         );
818       $cust_main->apply_credits;
819
820       #should check list for errors...
821       #$cust_main->suspend;
822       local $FS::svc_Common::noexport_hack = 1;
823       $cust_main->cancel('quiet'=>1);
824
825       my $perror = $placeholder->depended_delete;
826       warn "error removing provisioning jobs after decline: $perror" if $perror;
827       unless ( $perror ) {
828         $perror = $placeholder->delete;
829         warn "error removing placeholder after decline: $perror" if $perror;
830       }
831
832       return { 'error' => '_decline' };
833     }
834
835   }
836
837   if ( $reg_code ) {
838     $error = $reg_code->delete;
839     return { 'error' => $error } if $error;
840   }
841
842   $error = $placeholder->delete;
843   return { 'error' => $error } if $error;
844
845   if ( $conf->exists('signup-duplicate_cc-warn_hours') ) {
846     my $hours = $conf->config('signup-duplicate_cc-warn_hours');
847     my $ban = new FS::banned_pay $cust_main->_new_banned_pay_hashref;
848     $ban->end_date( int( time + $hours*3600 ) );
849     $ban->bantype('warn');
850     $ban->reason('signup-duplicate_cc-warn_hours');
851     $error = $ban->insert;
852     warn "WARNING: error inserting temporary banned_pay for ".
853          " signup-duplicate_cc-warn_hours (proceeding anyway): $error"
854       if $error;
855   }
856
857   my %return = ( 'error'          => '',
858                  'signup_service' => $svc_x,
859                  'custnum'        => $cust_main->custnum,
860                );
861
862   if ( $svc[0] ) {
863
864     $return{'svcnum'} = $svc[0]->svcnum;
865
866     if ( $svc_x eq 'svc_acct' ) {
867       $return{$_} = $svc[0]->$_() for qw( username _password );
868     } elsif ( $svc_x eq 'svc_phone' ) {
869       $return{$_} = $svc[0]->$_() for qw(countrycode phonenum sip_password pin);
870     } elsif ( $svc_x eq 'svc_pbx' ) {
871       #$return{$_} = $svc[0]->$_() for qw( ) #nothing yet
872      } else {
873       return {'error' => "configuration error: unknown signup service $svc_x"};
874       #die "unknown signup service $svc_x";
875       # return an error that's visible to someone somewhere
876     }
877
878   }
879
880   return \%return;
881
882 }
883
884 #false laziness w/ above
885 # fresh restart to support "free account" portals with 3.x/4.x-style
886 #  addressless accounts
887 # and a contact (for self-service login)
888 sub new_customer_minimal {
889   my $packet = shift;
890
891   my $conf = new FS::Conf;
892   my $svc_x = $conf->config('signup_server-service') || 'svc_acct';
893
894   if ( $svc_x eq 'svc_acct' ) {
895   
896     #things that aren't necessary in base class, but are for signup server
897       #return "Passwords don't match"
898       #  if $hashref->{'_password'} ne $hashref->{'_password2'}
899     return { 'error' => gettext('empty_password') }
900       unless length($packet->{'_password'});
901     # a bit inefficient for large numbers of pops
902     return { 'error' => gettext('no_access_number_selected') }
903       unless $packet->{'popnum'} || !scalar(qsearch('svc_acct_pop',{} ));
904
905   }
906   elsif ( $svc_x eq 'svc_pbx' ) {
907     #possibly some validation will be needed
908   }
909
910   my $agentnum;
911   if ( exists $packet->{'session_id'} ) {
912     my $cache = new FS::ClientAPI_SessionCache( {
913       'namespace' => 'FS::ClientAPI::Agent',
914     } );
915     my $session = $cache->get($packet->{'session_id'});
916     if ( $session ) {
917       $agentnum = $session->{'agentnum'};
918     } else {
919       return { 'error' => "Can't resume session" }; #better error message
920     }
921   } else {
922     $agentnum = $packet->{agentnum}
923                 || $conf->config('signup_server-default_agentnum');
924   }
925
926   #shares some stuff with htdocs/edit/process/cust_main.cgi... take any
927   # common that are still here and library them.
928
929   my $cust_main = new FS::cust_main ( {
930       'agentnum' => $agentnum,
931       'refnum'   => $packet->{refnum}
932                     || $conf->config('signup_server-default_refnum'),
933       'tagnum'   => [ FS::part_tag->default_tags ],
934       'payby'    => 'BILL',
935
936       map { $_ => $packet->{$_} } qw(
937         salesnum
938         last first company daytime night fax mobile
939         ss
940       ),
941
942   } );
943
944   if ( grep length($packet->{$_}), FS::cust_main->location_fields ) {
945     my $bill_hash;
946     foreach my $f (FS::cust_main->location_fields) {
947       $bill_hash->{$f} =  $packet->{$f};
948     }
949     my $bill_location = FS::cust_location->new($bill_hash);
950     $cust_main->set('bill_location' => $bill_location);
951     $cust_main->set('ship_location' => $bill_location);
952   }
953
954   my @invoicing_list = $packet->{'invoicing_list'}
955                          ? split( /\s*\,\s*/, $packet->{'invoicing_list'} )
956                          : ();
957
958   use Tie::RefHash;
959   tie my %hash, 'Tie::RefHash', ();
960   my @svc = ();
961
962   $packet->{'pkgpart'} =~ /^(\d+)$/ or '' =~ /^()$/;
963   my $pkgpart = $1;
964
965   if ( $pkgpart ) {
966
967     my $part_pkg =
968       qsearchs( 'part_pkg', { 'pkgpart' => $pkgpart } )
969         or return { 'error' => "WARNING: unknown pkgpart: $pkgpart" };
970     my $svcpart = $part_pkg->svcpart($svc_x);
971
972     my $cust_pkg = new FS::cust_pkg ( {
973       #later#'custnum' => $custnum,
974       'pkgpart'    => $packet->{'pkgpart'},
975     } );
976     #my $error = $cust_pkg->check;
977     #return { 'error' => $error } if $error;
978
979     #should be all auto-magic and shit
980     if ( $svc_x eq 'svc_acct' ) {
981
982       my $svc = new FS::svc_acct {
983         'svcpart'   => $svcpart,
984         map { $_ => $packet->{$_} }
985           qw( username _password sec_phrase popnum domsvc ),
986       };
987
988       push @svc, $svc;
989
990     } elsif ( $svc_x eq 'svc_phone' ) {
991
992       push @svc, new FS::svc_phone ( {
993         'svcpart' => $svcpart,
994          map { $_ => $packet->{$_} }
995            qw( countrycode phonenum sip_password pin ),
996       } );
997
998     } elsif ( $svc_x eq 'svc_pbx' ) {
999
1000       push @svc, new FS::svc_pbx ( {
1001           'svcpart' => $svcpart,
1002           map { $_ => $packet->{$_} } 
1003             qw( id title ),
1004           } );
1005     
1006     } else {
1007       die "unknown signup service $svc_x";
1008     }
1009
1010     foreach my $svc ( @svc ) {
1011       my $y = $svc->setdefault; # arguably should be in new method
1012       return { 'error' => $y } if $y && !ref($y);
1013       #$error = $svc->check;
1014       #return { 'error' => $error } if $error;
1015     }
1016
1017     use Tie::RefHash;
1018     tie my %hash, 'Tie::RefHash';
1019     $hash{ $cust_pkg } = \@svc;
1020
1021   }
1022
1023   my %opt = ();
1024   if ( $invoicing_list[0] && $packet->{'_password'} ) {
1025     $opt{'contact'} = [
1026       new FS::contact { 'first'        => $cust_main->first,
1027                         'last'         => $cust_main->get('last'),
1028                         '_password'    => $packet->{'_password'},
1029                         'emailaddress' => $invoicing_list[0],
1030                         'selfservice_access' => 'Y',
1031                       }
1032     ];
1033   }
1034
1035   my $error = $cust_main->insert(
1036     \%hash,
1037     \@invoicing_list,
1038     %opt,
1039   );
1040   return { 'error' => $error } if $error;
1041
1042   my $session = { 'custnum' => $cust_main->custnum };
1043
1044   my $session_id;
1045   do {
1046     $session_id = sha1_hex(time(). {}. rand(). $$)
1047   } until ( ! defined _myaccount_cache->get($session_id) ); #just in case
1048
1049   _cache->set( $session_id, $session, '1 hour' ); # 1 hour?
1050
1051   my %return = ( 'error'          => '',
1052                  'signup_service' => $svc_x,
1053                  'custnum'        => $cust_main->custnum,
1054                  'session_id'     => $session_id,
1055                );
1056
1057   if ( $svc[0] ) {
1058
1059     $return{'svcnum'} = $svc[0]->svcnum;
1060
1061     if ( $svc_x eq 'svc_acct' ) {
1062       $return{$_} = $svc[0]->$_() for qw( username _password );
1063     } elsif ( $svc_x eq 'svc_phone' ) {
1064       $return{$_} = $svc[0]->$_() for qw(countrycode phonenum sip_password pin);
1065     } elsif ( $svc_x eq 'svc_pbx' ) {
1066       #$return{$_} = $svc[0]->$_() for qw( ) #nothing yet
1067      } else {
1068       return {'error' => "configuration error: unknown signup service $svc_x"};
1069       #die "unknown signup service $svc_x";
1070       # return an error that's visible to someone somewhere
1071     }
1072
1073   }
1074
1075   return \%return;
1076
1077 }
1078
1079 use vars qw( $myaccount_cache );
1080 sub _myaccount_cache {
1081   $myaccount_cache ||= new FS::ClientAPI_SessionCache( {
1082                          'namespace' => 'FS::ClientAPI::MyAccount',
1083                        } );
1084 }
1085
1086 sub capture_payment {
1087   my $packet = shift;
1088
1089   warn "$me capture_payment called on $packet\n" if $DEBUG;
1090
1091   ###
1092   # identify processor/gateway from called back URL
1093   ###
1094
1095   my $conf = new FS::Conf;
1096
1097   my $payment_gateway;
1098   if ( my $gwnum = $conf->config('selfservice-payment_gateway') ) {
1099     $payment_gateway = qsearchs('payment_gateway', { 'gatewaynum' => $gwnum })
1100       or die "configured gatewaynum $gwnum not found!";
1101   }
1102   else {
1103     my $url = $packet->{url};
1104
1105     $payment_gateway = qsearchs('payment_gateway', 
1106         { 'gateway_callback_url' => popurl(0, $url) } 
1107       );
1108     if (!$payment_gateway) { 
1109
1110       my ( $processor, $login, $password, $action, @bop_options ) =
1111         $conf->config('business-onlinepayment');
1112       $action ||= 'normal authorization';
1113       pop @bop_options if scalar(@bop_options) % 2 && $bop_options[-1] =~ /^\s*$/;
1114       die "No real-time processor is enabled - ".
1115           "did you set the business-onlinepayment configuration value?\n"
1116         unless $processor;
1117
1118       $payment_gateway = new FS::payment_gateway( {
1119         gateway_namespace => $conf->config('business-onlinepayment-namespace'),
1120         gateway_module    => $processor,
1121         gateway_username  => $login,
1122         gateway_password  => $password,
1123         gateway_action    => $action,
1124         options   => [ ( @bop_options ) ],
1125       });
1126     }
1127   }
1128  
1129   die "No real-time third party processor is enabled - ".
1130       "did you set the business-onlinepayment configuration value?\n*"
1131     unless $payment_gateway->gateway_namespace eq 'Business::OnlineThirdPartyPayment';
1132
1133   ###
1134   # locate pending transaction
1135   ###
1136
1137   eval "use Business::OnlineThirdPartyPayment";
1138   die $@ if $@;
1139
1140   my $transaction =
1141     new Business::OnlineThirdPartyPayment( $payment_gateway->gateway_module,
1142                                            @{ [ $payment_gateway->options ] },
1143                                          );
1144
1145   my $paypendingnum = $transaction->reference($packet->{data});
1146
1147   my $cust_pay_pending =
1148     qsearchs('cust_pay_pending', { paypendingnum => $paypendingnum } );
1149
1150   unless ($cust_pay_pending) {
1151     my $bill_error = "No payment is being processed with id $paypendingnum".
1152                      "; Transaction aborted.";
1153     return { error => '_decline', bill_error => $bill_error };
1154   }
1155
1156   if ($cust_pay_pending->status ne 'thirdparty') {
1157     my $bill_error = "Payment with id $paypendingnum is not thirdparty, but ".
1158                      $cust_pay_pending->status.  "; Transaction aborted.";
1159     return { error => '_decline', bill_error => $bill_error };
1160   }
1161
1162   my $cust_main = $cust_pay_pending->cust_main;
1163   if ( $packet->{cancel} ) {
1164     # the user has chosen not to make this payment
1165     # (probably should be a separate API call, but I don't want to duplicate
1166     # all of the above...which should eventually go away)
1167     my $error = $cust_pay_pending->delete;
1168     # don't show any errors related to this; they're not meaningful
1169     warn "error canceling pending payment $paypendingnum: $error\n" if $error;
1170     return { 'error'      => '_cancel',
1171              'session_id' => $cust_pay_pending->session_id };
1172   } else {
1173     # create the payment
1174     my $bill_error =
1175       $cust_main->realtime_botpp_capture( $cust_pay_pending, 
1176         %{$packet->{data}},
1177         apply => 1,
1178     );
1179
1180     return { 'error'      => ( $bill_error->{bill_error} ? '_decline' : '' ),
1181              %$bill_error,
1182            };
1183   }
1184
1185 }
1186
1187 1;