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