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