7fad7b3089e8b6c8ca50c3d68b56e4e48fbc4950
[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     foreach my $payby (@paybys) {
348       warn "$me checking $payby payment fields\n" if $DEBUG > 1;
349       my $hide = 0;
350       if ( FS::payby->realtime($payby) ) {
351         my $gateway = 
352           $agent->payment_gateway( 'method'  => FS::payby->payby2bop($payby),
353                                    'nofatal' => 1,
354                                  );
355         if ( $gateway && $gateway->gateway_namespace
356                     eq 'Business::OnlineThirdPartyPayment'
357            ) {
358           warn "$me hiding $payby payment fields\n" if $DEBUG > 1;
359           $hide = 1;
360         }
361       }
362       push @{$signup_info->{'hide_payment_fields'}}, $hide;
363     } # foreach $payby
364     warn "$me done setting agent-specific payment flag\n" if $DEBUG > 1;
365
366     warn "$me setting agent-specific package list\n" if $DEBUG > 1;
367     $signup_info->{'part_pkg'} = $signup_info->{'agentnum2part_pkg'}{$agentnum}
368       unless @{ $signup_info->{'part_pkg'} };
369     warn "$me done setting agent-specific package list\n" if $DEBUG > 1;
370
371     warn "$me setting agent-specific adv. source list\n" if $DEBUG > 1;
372     $signup_info->{'part_referral'} =
373       [
374         map { $_->hashref }
375           qsearch( {
376                      'table'     => 'part_referral',
377                      'hashref'   => { 'disabled' => '' },
378                      'extra_sql' => "AND (    agentnum = $agentnum  ".
379                                     "      OR agentnum IS NULL    ) ",
380                    },
381                  )
382       ];
383     warn "$me done setting agent-specific adv. source list\n" if $DEBUG > 1;
384
385     $signup_info->{'agent_name'} = $agent->agent;
386
387     $signup_info->{'company_name'} = $conf->config('company_name', $agentnum);
388
389     #some of the above could probably be cached, too
390
391     my $signup_info_cache_agent = $cache->get("signup_info_cache_agent$agentnum");
392
393     if ( $signup_info_cache_agent ) {
394
395       warn "$me loading cached signup info for agentnum $agentnum\n"
396         if $DEBUG > 1;
397
398     } else {
399
400       warn "$me populating signup info cache for agentnum $agentnum\n"
401         if $DEBUG > 1;
402
403       $signup_info_cache_agent = {
404         #( map { $_ => scalar( $conf->config($_, $agentnum) ) }
405         #  qw( company_name ) ),
406         ( map { $_ => scalar( $conf->config("selfservice-$_", $agentnum ) ) }
407           qw( body_bgcolor box_bgcolor menu_bgcolor ) ),
408         ( map { $_ => join("\n", $conf->config("selfservice-$_", $agentnum ) ) }
409           qw( head body_header body_footer ) ),
410         ( map { $_ => join("\n", $conf->config("signup_server-$_", $agentnum ) ) }
411           qw( terms_of_service ) ),
412
413         ( map { $_ => scalar($conf->exists($_, $agentnum)) } 
414           qw(cust_main-require_phone agent-ship_address) ),
415       };
416
417       if ( $signup_info_cache_agent->{'agent-ship_address'} 
418            && $agent->agent_cust_main ) {
419
420         my $cust_main = $agent->agent_cust_main;
421         my $location = $cust_main->ship_location;
422         $signup_info_cache_agent->{"ship_$_"} = $location->get($_)
423           foreach qw( address1 city county state zip country );
424
425       }
426
427       $cache->set("signup_info_cache_agent$agentnum", $signup_info_cache_agent);
428
429     }
430
431     $signup_info->{$_} = $signup_info_cache_agent->{$_}
432       foreach keys %$signup_info_cache_agent;
433
434   }
435   # else {
436   # delete $signup_info->{'part_pkg'};
437   #}
438
439   warn "$me sorting package list\n" if $DEBUG > 1;
440   $signup_info->{'part_pkg'} = [ sort { $a->{pkg} cmp $b->{pkg} }  # case?
441                                       @{ $signup_info->{'part_pkg'} }
442                                ];
443   warn "$me done sorting package list\n" if $DEBUG > 1;
444
445   if ( exists $packet->{'session_id'} ) {
446     my $agent_signup_info = { %$signup_info };
447     delete $agent_signup_info->{agentnum2part_pkg};
448     $agent_signup_info->{'agent'} = $session->{'agent'};
449     return $agent_signup_info;
450   } 
451   elsif ( exists $packet->{'keys'} ) {
452     my @keys = @{ $packet->{'keys'} };
453     return { map { $_ => $signup_info->{$_} } @keys };
454   }
455   else {
456     return $signup_info;
457   }
458
459 }
460
461 sub domain_select_hash {
462   my $packet = shift;
463
464   my $response = {};
465
466   if ($packet->{pkgpart}) {
467     my $part_pkg = qsearchs('part_pkg' => { 'pkgpart' => $packet->{pkgpart} } );
468     #$packet->{svcpart} = $part_pkg->svcpart('svc_acct')
469     $packet->{svcpart} = $part_pkg->svcpart
470       if $part_pkg;
471   }
472
473   if ($packet->{svcpart}) {
474     my $part_svc = qsearchs('part_svc' => { 'svcpart' => $packet->{svcpart} } );
475     $response->{'domsvc'} = $part_svc->part_svc_column('domsvc')->columnvalue
476       if ($part_svc && $part_svc->part_svc_column('domsvc')->columnflag  eq 'D');
477   }
478
479   $response->{'domains'}
480     = { domain_select_hash FS::svc_acct( map { $_ => $packet->{$_} }
481                                                  qw(svcpart pkgnum)
482                                        ) };
483
484   $response;
485 }
486
487 sub new_customer {
488   my $packet = shift;
489
490   my $conf = new FS::Conf;
491   my $svc_x = $conf->config('signup_server-service') || 'svc_acct';
492
493   if ( $svc_x eq 'svc_acct' ) {
494   
495     #things that aren't necessary in base class, but are for signup server
496       #return "Passwords don't match"
497       #  if $hashref->{'_password'} ne $hashref->{'_password2'}
498     return { 'error' => gettext('empty_password') }
499       unless length($packet->{'_password'});
500     # a bit inefficient for large numbers of pops
501     return { 'error' => gettext('no_access_number_selected') }
502       unless $packet->{'popnum'} || !scalar(qsearch('svc_acct_pop',{} ));
503
504   }
505   elsif ( $svc_x eq 'svc_pbx' ) {
506     #possibly some validation will be needed
507   }
508
509   my $agentnum = get_agentnum($packet);
510   return $agentnum if ref($agentnum);
511
512   my ($bill_hash, $ship_hash);
513   foreach my $f (FS::cust_main->location_fields) {
514     # avoid having to change this in front-end code
515     $bill_hash->{$f} = $packet->{"bill_$f"} || $packet->{$f};
516     $ship_hash->{$f} = $packet->{"ship_$f"};
517   }
518
519   #shares some stuff with htdocs/edit/process/cust_main.cgi... take any
520   # common that are still here and library them.
521
522   my %cust_main = (
523     'agentnum' => $agentnum,
524     'refnum'   => $packet->{refnum}
525                   || $conf->config('signup_server-default_refnum'),
526     'tagnum'   => [ FS::part_tag->default_tags ],
527
528     ( map { $_ => $packet->{$_} } qw(
529             salesnum
530             ss stateid stateid_state
531             locale
532             referral_custnum comments
533           )
534     ),
535
536   );
537
538   my %insert_options = ();
539   if ( $packet->{payby} =~ /^(CARD|DCRD|CHEK|DCHK)$/ ) {
540     $insert_options{cust_payby} = [
541       new FS::cust_payby {
542         map { $_ => $packet->{$_} } qw(
543           payby
544           payinfo paycvv paydate payname paystate paytype
545           paystart_month paystart_year payissue
546           payip
547         ),
548       }
549     ];
550   }
551
552   my $template_custnum = $conf->config('signup_server-prepaid-template-custnum');
553   my $cust_main;
554   if ( $template_custnum && $packet->{prepaid_shortform} ) {
555
556     my $template_cust = qsearchs('cust_main', { 'custnum' => $template_custnum } );
557     return { 'error' => 'Configuration error' } unless $template_cust;
558     $cust_main = new FS::cust_main ( {
559       %cust_main,
560       map { $_ => $template_cust->$_ } qw( 
561         last first company daytime night fax mobile
562       ),
563     } );
564
565     $bill_hash = { $template_cust->bill_location->location_hash };
566     $ship_hash = { $template_cust->ship_location->location_hash };
567
568   } else {
569
570     $cust_main = new FS::cust_main ( {
571       %cust_main,
572       map { $_ => $packet->{$_} } qw(
573         last first company daytime night fax mobile
574         override_ban_warn
575       ),
576     } );
577   }
578
579   my $bill_location = FS::cust_location->new($bill_hash);
580   my $ship_location;
581   my $agent = qsearchs('agent', { 'agentnum' => $agentnum } );
582   if ( $conf->exists('agent-ship_address', $agentnum) 
583     && $agent->agent_custnum ) {
584
585     my $agent_cust_main = $agent->agent_cust_main;
586     my $prefix = length($agent_cust_main->ship_last) ? 'ship_' : '';
587     $ship_location = FS::cust_location->new({ 
588         $agent_cust_main->ship_location->location_hash
589     });
590
591   }
592   # we don't have an equivalent of the "same" checkbox in selfservice
593   # so is there a ship address, and if so, is it different from the billing 
594   # address?
595   elsif ( length($ship_hash->{address1}) > 0 and
596           grep { $bill_hash->{$_} ne $ship_hash->{$_} } keys(%$ship_hash)
597          ) {
598
599     $ship_location = FS::cust_location->new( $ship_hash );
600   
601   }
602   else {
603     $ship_location = $bill_location;
604   }
605
606   $cust_main->set('bill_location' => $bill_location);
607   $cust_main->set('ship_location' => $ship_location);
608
609   return { 'error' => "Illegal payment type" }
610     unless grep { $_ eq $packet->{'payby'} }
611                 $conf->config('signup_server-payby');
612
613   if (FS::payby->realtime($packet->{payby})
614     and not $conf->exists('signup_server-third_party_as_card')) {
615     my $payby = $packet->{payby};
616
617     my $agent = qsearchs('agent', { 'agentnum' => $agentnum });
618     return { 'error' => "Unknown reseller" }
619       unless $agent;
620
621     my $gw = $agent->payment_gateway( 'method'  => FS::payby->payby2bop($payby),
622                                       'nofatal' => 1,
623                                     );
624
625     $cust_main->payby('BILL')   # MCRD better?  no, that's for something else
626       if $gw && $gw->gateway_namespace eq 'Business::OnlineThirdPartyPayment';
627   }
628
629   return { 'error' => "CVV2 is required" }
630     if $cust_main->payby =~ /^(CARD|DCRD)$/
631     && ! $cust_main->paycvv
632     && $conf->exists('signup-require_cvv');
633
634   my @invoicing_list = $packet->{'invoicing_list'}
635                          ? split( /\s*\,\s*/, $packet->{'invoicing_list'} )
636                          : ();
637
638   my @exempt_groups = grep /\S/, $conf->config('tax-cust_exempt-groups');
639   my @tax_exempt = grep { $packet->{"tax_$_"} eq 'Y' } @exempt_groups;
640   $insert_options{'tax_exemption'} = {
641     map { $_ => $packet->{"tax_$_".'_num'} } @tax_exempt
642   };
643
644   $packet->{'pkgpart'} =~ /^(\d+)$/ or '' =~ /^()$/;
645   my $pkgpart = $1;
646   return { 'error' => 'Please select a package' } unless $pkgpart; #msgcat
647
648   my $part_pkg =
649     qsearchs( 'part_pkg', { 'pkgpart' => $pkgpart } )
650       or return { 'error' => "WARNING: unknown pkgpart: $pkgpart" };
651
652   my $reg_code = '';
653   if ( $packet->{'reg_code'} ) {
654     $reg_code = qsearchs( 'reg_code', { 'code'     => $packet->{'reg_code'},
655                                         'agentnum' => $agentnum,             } )
656       or return { 'error' => 'Unknown registration code' };
657   }
658
659   my $cust_pkg = new FS::cust_pkg ( {
660     #later#'custnum' => $custnum,
661     'pkgpart'    => $packet->{'pkgpart'},
662     'promo_code' => $packet->{'promo_code'},
663     'reg_code'   => $packet->{'reg_code'},
664   } );
665   #my $error = $cust_pkg->check;
666   #return { 'error' => $error } if $error;
667
668   my @svc = ();
669   unless ( $svc_x eq 'none' ) {
670
671     my $svcpart = $part_pkg->svcpart($svc_x);
672     #should be all auto-magic and shit
673     if ( $svc_x eq 'svc_acct' ) {
674
675       my $svc = new FS::svc_acct {
676         'svcpart'   => $svcpart,
677         map { $_ => $packet->{$_} }
678           qw( username _password sec_phrase popnum domsvc ),
679       };
680       
681       my $error = $svc->is_password_allowed($packet->{_password});
682       return { error => $error } if $error;
683
684       my @acct_snarf;
685       my $snarfnum = 1;
686       while (    exists($packet->{"snarf_machine$snarfnum"})
687               && length($packet->{"snarf_machine$snarfnum"}) ) {
688         my $acct_snarf = new FS::acct_snarf ( {
689           'machine'   => $packet->{"snarf_machine$snarfnum"},
690           'protocol'  => $packet->{"snarf_protocol$snarfnum"},
691           'username'  => $packet->{"snarf_username$snarfnum"},
692           '_password' => $packet->{"snarf_password$snarfnum"},
693         } );
694         $snarfnum++;
695         push @acct_snarf, $acct_snarf;
696       }
697       $svc->child_objects( \@acct_snarf );
698       push @svc, $svc;
699
700     } elsif ( $svc_x eq 'svc_phone' ) {
701
702       push @svc, new FS::svc_phone ( {
703         'svcpart' => $svcpart,
704          map { $_ => $packet->{$_} }
705            qw( countrycode phonenum sip_password pin ),
706       } );
707
708     } elsif ( $svc_x eq 'svc_pbx' ) {
709
710       push @svc, new FS::svc_pbx ( {
711           'svcpart' => $svcpart,
712           map { $_ => $packet->{$_} } 
713             qw( id title ),
714           } );
715   
716     } else {
717       die "unknown signup service $svc_x";
718     }
719
720   }
721
722   if ($packet->{'mac_addr'} && $conf->exists('signup_server-mac_addr_svcparts'))
723   {
724
725     my %mac_addr_svcparts = map { $_ => 1 }
726                             $conf->config('signup_server-mac_addr_svcparts');
727     my @pkg_svc = grep { $_->quantity && $mac_addr_svcparts{$_->svcpart} }
728                   $cust_pkg->part_pkg->pkg_svc;
729
730     return { 'error' => 'No service defined to assign mac address' }
731       unless @pkg_svc;
732
733     my $svc = new FS::svc_acct {
734       'svcpart'   => $pkg_svc[0]->svcpart, #multiple matches? alas..
735       'username'  => $packet->{'mac_addr'},
736       '_password' => '', #blank as requested (set passwordmin to 0)
737     };
738
739     push @svc, $svc;
740
741   }
742
743   foreach my $svc ( @svc ) {
744     my $y = $svc->setdefault; # arguably should be in new method
745     return { 'error' => $y } if $y && !ref($y);
746     #$error = $svc->check;
747     #return { 'error' => $error } if $error;
748   }
749
750   #setup a job dependancy to delay provisioning
751   my $placeholder = new FS::queue ( {
752     'job'    => 'FS::ClientAPI::Signup::__placeholder',
753     'status' => 'locked',
754   } );
755   my $error = $placeholder->insert;
756   return { 'error' => $error } if $error;
757
758   use Tie::RefHash;
759   tie my %hash, 'Tie::RefHash';
760   %hash = ( $cust_pkg => \@svc );
761   #msgcat
762   $error = $cust_main->insert(
763     \%hash,
764     \@invoicing_list,
765     'depend_jobnum' => $placeholder->jobnum,
766      %insert_options,
767   );
768   if ( $error ) {
769     my $perror = $placeholder->delete;
770     $error .= " (Additionally, error removing placeholder: $perror)" if $perror;
771     return { 'error' => $error };
772   }
773
774   if ( $conf->exists('signup_server-realtime') ) {
775
776     #warn "$me Billing customer...\n" if $Debug;
777
778     my @cust_bill;
779     my $bill_error = $cust_main->bill(
780       'depend_jobnum' => $placeholder->jobnum,
781       'return_bill'   => \@cust_bill,
782     );
783     #warn "$me error billing new customer: $bill_error"
784     #  if $bill_error;
785
786     $bill_error = $cust_main->apply_payments_and_credits;
787     #warn "$me error applying payments and credits for".
788     #     " new customer: $bill_error"
789     #  if $bill_error;
790
791     unless ( $packet->{payby} eq 'PREPAY' ) {
792       $bill_error = $cust_main->realtime_collect(
793          method        => FS::payby->payby2bop( $packet->{payby} ),
794          depend_jobnum => $placeholder->jobnum,
795          selfservice   => 1,
796       );
797       #warn "$me error collecting from new customer: $bill_error"
798       #  if $bill_error;
799     }
800
801     if ($bill_error && ref($bill_error) eq 'HASH') {
802       return { 'error' => '_collect',
803                ( map { $_ => $bill_error->{$_} }
804                  qw(popup_url reference collectitems)
805                ),
806                amount => $cust_main->balance,
807              };
808     }
809
810     $bill_error = $cust_main->apply_payments_and_credits;
811     #warn "$me error applying payments and credits for".
812     #     " new customer: $bill_error"
813     #  if $bill_error;
814
815     if ( $cust_main->balance > 0 ) {
816
817       #this used to apply a credit, but now we can void invoices...
818       foreach my $cust_bill (@cust_bill) {
819         my $voiderror = $cust_bill->void('automatic payment failed');
820         warn "Error voiding cust bill after decline: $voiderror" if $voiderror;
821       }
822
823       #should check list for errors...
824       #$cust_main->suspend;
825       local $FS::svc_Common::noexport_hack = 1;
826       $cust_main->cancel('quiet'=>1);
827
828       my $perror = $placeholder->depended_delete;
829       warn "error removing provisioning jobs after decline: $perror" if $perror;
830       unless ( $perror ) {
831         $perror = $placeholder->delete;
832         warn "error removing placeholder after decline: $perror" if $perror;
833       }
834
835       return { 'error' => '_decline' };
836     }
837
838   }
839
840   if ( $reg_code ) {
841     $error = $reg_code->delete;
842     return { 'error' => $error } if $error;
843   }
844
845   $error = $placeholder->delete;
846   return { 'error' => $error } if $error;
847
848   if ( $conf->exists('signup-duplicate_cc-warn_hours') ) {
849     my $hours = $conf->config('signup-duplicate_cc-warn_hours');
850     my $ban = new FS::banned_pay $cust_main->_new_banned_pay_hashref;
851     $ban->end_date( int( time + $hours*3600 ) );
852     $ban->bantype('warn');
853     $ban->reason('signup-duplicate_cc-warn_hours');
854     $error = $ban->insert;
855     warn "WARNING: error inserting temporary banned_pay for ".
856          " signup-duplicate_cc-warn_hours (proceeding anyway): $error"
857       if $error;
858   }
859
860   my %return = ( 'error'          => '',
861                  'signup_service' => $svc_x,
862                  'custnum'        => $cust_main->custnum,
863                );
864
865   if ( $svc[0] ) {
866
867     $return{'svcnum'} = $svc[0]->svcnum;
868
869     if ( $svc_x eq 'svc_acct' ) {
870       $return{$_} = $svc[0]->$_() for qw( username _password );
871     } elsif ( $svc_x eq 'svc_phone' ) {
872       $return{$_} = $svc[0]->$_() for qw(countrycode phonenum sip_password pin);
873     } elsif ( $svc_x eq 'svc_pbx' ) {
874       #$return{$_} = $svc[0]->$_() for qw( ) #nothing yet
875      } else {
876       return {'error' => "configuration error: unknown signup service $svc_x"};
877       #die "unknown signup service $svc_x";
878       # return an error that's visible to someone somewhere
879     }
880
881   }
882
883   return \%return;
884
885 }
886
887 #false laziness w/ above
888 # fresh restart to support "free account" portals with 3.x/4.x-style
889 #  addressless accounts
890 # and a contact (for self-service login)
891 sub new_customer_minimal {
892   my $packet = shift;
893
894   my $conf = new FS::Conf;
895   my $svc_x = $conf->config('signup_server-service') || 'svc_acct';
896
897   if ( $svc_x eq 'svc_acct' ) {
898   
899     #things that aren't necessary in base class, but are for signup server
900       #return "Passwords don't match"
901       #  if $hashref->{'_password'} ne $hashref->{'_password2'}
902     return { 'error' => gettext('empty_password') }
903       unless length($packet->{'_password'});
904     # a bit inefficient for large numbers of pops
905     return { 'error' => gettext('no_access_number_selected') }
906       unless $packet->{'popnum'} || !scalar(qsearch('svc_acct_pop',{} ));
907
908   }
909   elsif ( $svc_x eq 'svc_pbx' ) {
910     #possibly some validation will be needed
911   }
912
913   my $agentnum = get_agentnum($packet);
914   return $agentnum if ref($agentnum);
915
916   #shares some stuff with htdocs/edit/process/cust_main.cgi... take any
917   # common that are still here and library them.
918
919   my $cust_main = new FS::cust_main ( {
920       'agentnum' => $agentnum,
921       'refnum'   => $packet->{refnum}
922                     || $conf->config('signup_server-default_refnum'),
923       'tagnum'   => [ FS::part_tag->default_tags ],
924
925       map { $_ => $packet->{$_} } qw(
926         salesnum
927         last first company daytime night fax mobile
928         ss stateid stateid_state
929
930         locale
931       ),
932
933   } );
934
935   my %opt = ();
936   if ( $packet->{payby} =~ /^(CARD|DCRD|CHEK|DCHK)$/ ) {
937     $opt{cust_payby} = [
938       new FS::cust_payby {
939         map { $_ => $packet->{$_} } qw(
940           payby
941           payinfo paycvv paydate payname paystate paytype
942           paystart_month paystart_year payissue
943           payip
944         ),
945       }
946     ];
947   }
948
949   if ( grep length($packet->{$_}), FS::cust_main->location_fields ) {
950     my $bill_hash;
951     foreach my $f (FS::cust_main->location_fields) {
952       $bill_hash->{$f} =  $packet->{$f};
953     }
954     my $bill_location = FS::cust_location->new($bill_hash);
955     $cust_main->set('bill_location' => $bill_location);
956     $cust_main->set('ship_location' => $bill_location);
957   }
958
959   my @invoicing_list = $packet->{'invoicing_list'}
960                          ? split( /\s*\,\s*/, $packet->{'invoicing_list'} )
961                          : ();
962
963   use Tie::RefHash;
964   tie my %hash, 'Tie::RefHash', ();
965   my @svc = ();
966
967   $packet->{'pkgpart'} =~ /^(\d+)$/ or '' =~ /^()$/;
968   my $pkgpart = $1;
969
970   if ( $pkgpart ) {
971
972     my $part_pkg =
973       qsearchs( 'part_pkg', { 'pkgpart' => $pkgpart } )
974         or return { 'error' => "WARNING: unknown pkgpart: $pkgpart" };
975
976     my $cust_pkg = new FS::cust_pkg ( {
977       #later#'custnum' => $custnum,
978       'pkgpart'    => $packet->{'pkgpart'},
979     } );
980     #my $error = $cust_pkg->check;
981     #return { 'error' => $error } if $error;
982
983     unless ( $svc_x eq 'none' ) {
984
985       my $svcpart = $part_pkg->svcpart($svc_x);
986       #should be all auto-magic and shit
987       if ( $svc_x eq 'svc_acct' ) {
988
989         my $svc = new FS::svc_acct {
990           'svcpart'   => $svcpart,
991           map { $_ => $packet->{$_} }
992             qw( username _password sec_phrase popnum domsvc ),
993         };
994
995         push @svc, $svc;
996
997       } elsif ( $svc_x eq 'svc_phone' ) {
998
999         push @svc, new FS::svc_phone ( {
1000           'svcpart' => $svcpart,
1001            map { $_ => $packet->{$_} }
1002              qw( countrycode phonenum sip_password pin ),
1003         } );
1004
1005       } elsif ( $svc_x eq 'svc_pbx' ) {
1006
1007         push @svc, new FS::svc_pbx ( {
1008             'svcpart' => $svcpart,
1009             map { $_ => $packet->{$_} } 
1010               qw( id title ),
1011             } );
1012     
1013       } else {
1014         die "unknown signup service $svc_x";
1015       }
1016
1017     }
1018
1019     foreach my $svc ( @svc ) {
1020       my $y = $svc->setdefault; # arguably should be in new method
1021       return { 'error' => $y } if $y && !ref($y);
1022       #$error = $svc->check;
1023       #return { 'error' => $error } if $error;
1024     }
1025
1026     use Tie::RefHash;
1027     tie my %hash, 'Tie::RefHash';
1028     $hash{ $cust_pkg } = \@svc;
1029
1030   }
1031
1032   if ( $invoicing_list[0] && $packet->{'_password'} ) {
1033     $opt{'contact'} = [
1034       new FS::contact { 'first'        => $cust_main->first,
1035                         'last'         => $cust_main->get('last'),
1036                         '_password'    => $packet->{'_password'},
1037                         'emailaddress' => $invoicing_list[0],
1038                         'selfservice_access' => 'Y',
1039                       }
1040     ];
1041   }
1042
1043   my $error = $cust_main->insert(
1044     \%hash,
1045     \@invoicing_list,
1046     %opt,
1047   );
1048   return { 'error' => $error } if $error;
1049
1050   my $session = { 'custnum' => $cust_main->custnum };
1051
1052   my $session_id;
1053   do {
1054     $session_id = sha512_hex(time(). {}. rand(). $$)
1055   } until ( ! defined _myaccount_cache->get($session_id) ); #just in case
1056
1057   _myaccount_cache->set( $session_id, $session, '1 hour' ); # 1 hour?
1058
1059   my %return = ( 'error'          => '',
1060                  'signup_service' => $svc_x,
1061                  'custnum'        => $cust_main->custnum,
1062                  'session_id'     => $session_id,
1063                  map { $_ => $cust_main->$_ } qw( first last company ),
1064                );
1065
1066   if ( $svc[0] ) {
1067
1068     $return{'svcnum'} = $svc[0]->svcnum;
1069
1070     if ( $svc_x eq 'svc_acct' ) {
1071       $return{$_} = $svc[0]->$_() for qw( username _password );
1072     } elsif ( $svc_x eq 'svc_phone' ) {
1073       $return{$_} = $svc[0]->$_() for qw(countrycode phonenum sip_password pin);
1074     } elsif ( $svc_x eq 'svc_pbx' ) {
1075       #$return{$_} = $svc[0]->$_() for qw( ) #nothing yet
1076      } else {
1077       return {'error' => "configuration error: unknown signup service $svc_x"};
1078       #die "unknown signup service $svc_x";
1079       # return an error that's visible to someone somewhere
1080     }
1081
1082   }
1083
1084   return \%return;
1085
1086 }
1087
1088 use vars qw( $myaccount_cache );
1089 sub _myaccount_cache {
1090   $myaccount_cache ||= new FS::ClientAPI_SessionCache( {
1091                          'namespace' => 'FS::ClientAPI::MyAccount',
1092                        } );
1093 }
1094
1095 sub capture_payment {
1096   my $packet = shift;
1097
1098   warn "$me capture_payment called on $packet\n" if $DEBUG;
1099
1100   ###
1101   # identify processor/gateway from called back URL
1102   ###
1103
1104   my $conf = new FS::Conf;
1105
1106   my $url = $packet->{url};
1107   my $payment_gateway = $payment_gateway = qsearchs('payment_gateway', 
1108         { 'gateway_callback_url' => popurl(0, $url) } 
1109       );
1110   if (!$payment_gateway) { 
1111
1112     my ( $processor, $login, $password, $action, @bop_options ) =
1113       $conf->config('business-onlinepayment');
1114     $action ||= 'normal authorization';
1115     pop @bop_options if scalar(@bop_options) % 2 && $bop_options[-1] =~ /^\s*$/;
1116     die "No real-time processor is enabled - ".
1117         "did you set the business-onlinepayment configuration value?\n"
1118       unless $processor;
1119
1120     $payment_gateway = new FS::payment_gateway( {
1121       gateway_namespace => $conf->config('business-onlinepayment-namespace'),
1122       gateway_module    => $processor,
1123       gateway_username  => $login,
1124       gateway_password  => $password,
1125       gateway_action    => $action,
1126       options   => [ ( @bop_options ) ],
1127     });
1128   }
1129  
1130   die "No real-time third party processor is enabled - ".
1131       "did you set the business-onlinepayment configuration value?\n*"
1132     unless $payment_gateway->gateway_namespace eq 'Business::OnlineThirdPartyPayment';
1133
1134   ###
1135   # locate pending transaction
1136   ###
1137
1138   eval "use Business::OnlineThirdPartyPayment";
1139   die $@ if $@;
1140
1141   my $transaction =
1142     new Business::OnlineThirdPartyPayment( $payment_gateway->gateway_module,
1143                                            @{ [ $payment_gateway->options ] },
1144                                          );
1145
1146   my $paypendingnum = $transaction->reference($packet->{data});
1147
1148   my $cust_pay_pending =
1149     qsearchs('cust_pay_pending', { paypendingnum => $paypendingnum } );
1150
1151   unless ($cust_pay_pending) {
1152     my $bill_error = "No payment is being processed with id $paypendingnum".
1153                      "; Transaction aborted.";
1154     return { error => '_decline', bill_error => $bill_error };
1155   }
1156
1157   if ($cust_pay_pending->status ne 'thirdparty') {
1158     my $bill_error = "Payment with id $paypendingnum is not thirdparty, but ".
1159                      $cust_pay_pending->status.  "; Transaction aborted.";
1160     return { error => '_decline', bill_error => $bill_error };
1161   }
1162
1163   my $cust_main = $cust_pay_pending->cust_main;
1164   if ( $packet->{cancel} ) {
1165     # the user has chosen not to make this payment
1166     # (probably should be a separate API call, but I don't want to duplicate
1167     # all of the above...which should eventually go away)
1168     my $error = $cust_pay_pending->delete;
1169     # don't show any errors related to this; they're not meaningful
1170     warn "error canceling pending payment $paypendingnum: $error\n" if $error;
1171     return { 'error'      => '_cancel',
1172              'session_id' => $cust_pay_pending->session_id };
1173   } else {
1174     # create the payment
1175     my $bill_error =
1176       $cust_main->realtime_botpp_capture( $cust_pay_pending, 
1177         %{$packet->{data}},
1178         apply => 1,
1179     );
1180
1181     return { 'error'      => ( $bill_error->{bill_error} ? '_decline' : '' ),
1182              %$bill_error,
1183            };
1184   }
1185
1186 }
1187
1188 =item get_agentnum PACKET
1189
1190 Given a PACKET from the signup server, looks up the agentnum to use for signing
1191 up a customer. This will use 'session_id' if the agent is authenticated,
1192 otherwise 'agentnum', otherwise the 'signup_server-default_agentnum' config. If
1193 the agent can't be found, returns an error packet.
1194
1195 =cut
1196
1197 sub get_agentnum {
1198   my $packet = shift;
1199   my $conf = new FS::Conf;
1200   my $agentnum;
1201   if ( exists $packet->{'session_id'} ) {
1202     my $cache = new FS::ClientAPI_SessionCache( {
1203       'namespace' => 'FS::ClientAPI::Agent',
1204     } );
1205     my $session = $cache->get($packet->{'session_id'});
1206     if ( $session ) {
1207       $agentnum = $session->{'agentnum'};
1208     } else {
1209       return { 'error' => "Can't resume session" }; #better error message
1210     }
1211   } else {
1212     $agentnum = $packet->{agentnum}
1213                 || $conf->config('signup_server-default_agentnum');
1214   }
1215   if ( $agentnum and FS::agent->count('agentnum = ?', $agentnum) ) {
1216     return $agentnum;
1217   }
1218   return { 'error' => 'Signup is not configured' };
1219 }
1220
1221 =item new_prospect PACKET
1222
1223 Creates a new L<FS::prospect_main> entry. PACKET must contain:
1224
1225 - either agentnum or session_id; if not, signup_server-default_agentnum will
1226 be used and must not be empty
1227
1228 - either refnum or referral_title; if not, signup_server-default_refnum will
1229 be used and must not be empty
1230
1231 - last and first (names), and optionally company and title
1232
1233 - address1, city, state, country, zip, and optionally address2
1234
1235 - emailaddress
1236
1237 and can also contain:
1238
1239 - one or more of phone_daytime, phone_night, phone_mobile, and phone_fax
1240
1241 - a 'comment' (will be attached to the contact)
1242
1243 State and country will be normalized to Freeside state/country codes if
1244 necessary.
1245
1246 =cut
1247
1248 sub new_prospect {
1249
1250   my $packet = shift;
1251   warn "$me new_prospect called\n".Dumper($packet) if $DEBUG;
1252
1253   my $oldAutoCommit = $FS::UID::AutoCommit;
1254   local $FS::UID::AutoCommit = 0;
1255   my $dbh = dbh;
1256   my $conf = FS::Conf->new;
1257
1258   my $error;
1259
1260   my $agentnum = get_agentnum($packet);
1261   return $agentnum if ref $agentnum;
1262   my $refnum;
1263   if ( my $title = $packet->{referral_title} ) {
1264     my $part_referral = qsearchs('part_referral', {
1265         'agentnum'  => $agentnum,
1266         'title'     => $title,
1267     });
1268     $part_referral ||= qsearchs('part_referral', {
1269         'agentnum'  => '',
1270         'title'     => $title,
1271     });
1272     if (!$part_referral) {
1273       $part_referral = FS::part_referral->new({
1274         'agentnum' => $agentnum,
1275         'title'    => $title,
1276         'referral' => $title,
1277       });
1278       $error = $part_referral->insert;
1279       if ( $error ) {
1280         warn "ERROR: could not create referral type '$title': $error\n";
1281       }
1282     }
1283     $refnum = $part_referral->refnum;
1284   } elsif ( $packet->{refnum} ) {
1285     $refnum = $packet->{refnum};
1286   }
1287   $refnum ||= $conf->config('signup_server-default_refnum');
1288   return { error => "Signup referral type is not configured" } if !$refnum;
1289
1290   my $prospect = FS::prospect_main->new({
1291       'agentnum' => $agentnum,
1292       'refnum'   => $refnum,
1293       'company'  => $packet->{company},
1294   });
1295
1296   my $location = FS::cust_location->new;
1297   foreach ( qw(address1 address2 city county zip ) ) {
1298     $location->set($_, $packet->{$_});
1299   }
1300   # normalize country and state if they're not already ISO codes
1301   # easier than doing it on the client side--we already have the tables here
1302   my $country = $packet->{country};
1303   my $state = $packet->{state};
1304   if (length($country) > 2) {
1305     # it likes title case
1306     $country = join(' ', map ucfirst, split(/\s+/, $country));
1307     my $lsc = Locale::SubCountry->new($country);
1308     if ($lsc) {
1309       $country = uc($lsc->country_code);
1310
1311       if ($lsc->has_sub_countries) {
1312         if ( $lsc->full_name($state) eq 'unknown' ) {
1313           # then we were probably given a full name, so resolve it
1314           $state = $lsc->code($state);
1315           if ( $state eq 'unknown' ) {
1316             # doesn't resolve as a full name either, return an error
1317             $error = "Unknown state: ".$packet->{state};
1318           } else {
1319             $state = uc($state);
1320           }
1321         }
1322       } # else state doesn't matter
1323     } else {
1324       # couldn't find the country in LSC
1325       $error = "Unknown country: $country";
1326     }
1327   }
1328   $location->set('country', $country);
1329   $location->set('state', $state);
1330
1331   $error ||= $prospect->insert( cust_location => $location );
1332   return { error => $error } if $error;
1333
1334   my $contact = FS::contact->new({
1335       prospectnum   => $prospect->prospectnum,
1336       locationnum   => $location->locationnum,
1337       invoice_dest  => 'Y',
1338   });
1339   # use emailaddress pseudo-field behavior here
1340   foreach (qw(last first title emailaddress comment)) {
1341     $contact->set($_, $packet->{$_});
1342   }
1343   $error = $contact->insert;
1344   if ( $error ) {
1345     $dbh->rollback if $oldAutoCommit;
1346     return { error => $error };
1347   }
1348
1349   foreach my $phone_type (qsearch('phone_type', {})) {
1350     my $key = 'phone_' . lc($phone_type->typename);
1351     my $phonenum = $packet->{$key};
1352     if ( $phonenum ) {
1353       # just to not have to supply country code from the other end
1354       my $number = Number::Phone->new($location->country, $phonenum);
1355       if (!$number) {
1356         $error = 'invalid phone number';
1357       } else {
1358         my $phone = FS::contact_phone->new({
1359             contactnum    => $contact->contactnum,
1360             phonenum      => $phonenum,
1361             countrycode   => $number->country_code,
1362             phonetypenum  => $phone_type->phonetypenum,
1363         });
1364         $error = $phone->insert;
1365       }
1366       if ( $error ) {
1367         $dbh->rollback if $oldAutoCommit;
1368         return { error => $phone_type->typename . ' phone: ' . $error };
1369       }
1370     }
1371   } # foreach $phone_type
1372   
1373   $dbh->commit if $oldAutoCommit;
1374   return { prospectnum => $prospect->prospectnum };
1375 }
1376
1377 1;