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