limit password reuse, core and svc_acct, #29354
[freeside.git] / FS / FS / ClientAPI / MyAccount.pm
1 package FS::ClientAPI::MyAccount;
2
3 use 5.008; #require 5.8+ for Time::Local 1.05+
4 use strict;
5 use vars qw( $cache $DEBUG $me );
6 use subs qw( _cache _provision );
7 use IO::Scalar;
8 use Data::Dumper;
9 use Digest::MD5 qw(md5_hex);
10 use Digest::SHA qw(sha512_hex);
11 use Date::Format;
12 use Time::Duration;
13 use Time::Local qw(timelocal_nocheck);
14 use Business::CreditCard;
15 use HTML::Entities;
16 use Text::CSV_XS;
17 use Spreadsheet::WriteExcel;
18 use OLE::Storage_Lite;
19 use FS::UI::Web::small_custview qw(small_custview); #less doh
20 use FS::UI::Web;
21 use FS::UI::bytecount qw( display_bytecount );
22 use FS::Conf;
23 #use FS::UID qw(dbh);
24 use FS::Record qw(qsearch qsearchs dbh);
25 use FS::Msgcat qw(gettext);
26 use FS::Misc qw(card_types money_pretty);
27 use FS::Misc::DateTime qw(parse_datetime);
28 use FS::TicketSystem;
29 use FS::ClientAPI_SessionCache;
30 use FS::cust_svc;
31 use FS::svc_acct;
32 use FS::svc_forward;
33 use FS::svc_domain;
34 use FS::svc_phone;
35 use FS::svc_external;
36 use FS::svc_dsl;
37 use FS::dsl_device;
38 use FS::part_svc;
39 use FS::cust_main;
40 use FS::cust_bill;
41 use FS::legacy_cust_bill;
42 use FS::cust_main_county;
43 use FS::part_pkg;
44 use FS::cust_pkg;
45 use FS::payby;
46 use FS::acct_rt_transaction;
47 use FS::msg_template;
48 use FS::contact;
49 use FS::cust_contact;
50 use FS::cust_location;
51 use FS::cust_payby;
52
53 # for code organization
54 use FS::ClientAPI::MyAccount::contact;
55 use FS::ClientAPI::MyAccount::quotation;
56
57 $DEBUG = 0;
58 $me = '[FS::ClientAPI::MyAccount]';
59
60 use vars qw( @cust_main_editable_fields @location_editable_fields );
61 @cust_main_editable_fields = qw(
62   first last company daytime night fax mobile
63   locale
64   payby payinfo payname paystart_month paystart_year payissue payip
65   ss paytype paystate stateid stateid_state
66 );
67 @location_editable_fields = qw(
68   address1 address2 city county state zip country
69 );
70
71
72 BEGIN { #preload to reduce time customer_info takes
73   if ( $FS::TicketSystem::system ) {
74     warn "$me: initializing ticket system\n" if $DEBUG;
75     FS::TicketSystem->init();
76   }
77 }
78
79 sub _cache {
80   $cache ||= new FS::ClientAPI_SessionCache( {
81                'namespace' => 'FS::ClientAPI::MyAccount',
82              } );
83 }
84
85 sub skin_info {
86   my $p = shift;
87
88   my($context, $session, $custnum) = _custoragent_session_custnum($p);
89   #return { 'error' => $session } if $context eq 'error';
90
91   my $agentnum = '';
92   if ( $context eq 'customer' && $custnum ) {
93
94     my $sth = dbh->prepare('SELECT agentnum FROM cust_main WHERE custnum = ?')
95       or die dbh->errstr;
96
97     $sth->execute($custnum) or die $sth->errstr;
98
99     $agentnum = $sth->fetchrow_arrayref->[0]
100       or die "no agentnum for custnum $custnum";
101
102   #} elsif ( $context eq 'agent' ) {
103   } elsif ( defined($p->{'agentnum'}) and $p->{'agentnum'} =~ /^(\d+)$/ ) {
104     $agentnum = $1;
105   }
106   $p->{'agentnum'} = $agentnum;
107
108   my $conf = new FS::Conf;
109
110   #false laziness w/Signup.pm
111
112   my $skin_info_cache_agent = _cache->get("skin_info_cache_agent$agentnum");
113
114   if ( $skin_info_cache_agent ) {
115
116     warn "$me loading cached skin info for agentnum $agentnum\n"
117       if $DEBUG > 1;
118
119   } else {
120
121     warn "$me populating skin info cache for agentnum $agentnum\n"
122       if $DEBUG > 1;
123
124     $skin_info_cache_agent = {
125       'agentnum' => $agentnum,
126       ( map { $_ => scalar( $conf->config($_, $agentnum) ) }
127         qw( company_name date_format ) ),
128       ( map { $_ => scalar( $conf->config("selfservice-$_", $agentnum ) ) }
129         qw( body_bgcolor box_bgcolor stripe1_bgcolor stripe2_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       'menu_disable' => [ $conf->config('selfservice-menu_disable',$agentnum) ],
135       ( map { $_ => $conf->exists("selfservice-$_", $agentnum ) }
136         qw( menu_skipblanks menu_skipheadings menu_nounderline no_logo enable_payment_without_balance )
137       ),
138       ( map { $_ => scalar($conf->config_binary("selfservice-$_", $agentnum)) }
139         qw( title_left_image title_right_image
140             menu_top_image menu_body_image menu_bottom_image
141           )
142       ),
143       'logo' => scalar($conf->config_binary('logo.png', $agentnum )),
144       ( map { $_ => join("\n", $conf->config("selfservice-$_", $agentnum ) ) }
145         qw( head body_header body_footer company_address ) ),
146       'money_char' => $conf->config("money_char") || '$',
147       'menu' => join("\n", $conf->config("ng_selfservice-menu", $agentnum ) ) ||
148                 'main.php Home
149
150                  services.php Services
151                  services.php My Services
152                  services_new.php Order a new service
153
154                  personal.php Profile
155                  personal.php Personal Information
156                  password.php Change Password
157
158                  payment.php Payments
159                  payment_cc.php Credit Card Payment
160                  payment_ach.php Electronic Check Payment
161                  payment_paypal.php PayPal Payment
162                  payment_webpay.php Webpay Payments
163
164                  usage.php Usage
165                  usage_data.php Data usage
166                  usage_cdr.php Call usage
167
168                  tickets.php Help Desk
169                  tickets.php Open Tickets
170                  tickets_resolved.php Resolved Tickets
171                  ticket_create.php Create a new ticket
172
173                  docs.php FAQs
174
175                  logout.php Logout
176                 ',
177     };
178
179     _cache->set("skin_info_cache_agent$agentnum", $skin_info_cache_agent);
180
181   }
182
183   #{ %$skin_info_cache_agent };
184   $skin_info_cache_agent;
185
186 }
187
188 sub login_info {
189   my $p = shift;
190
191   my $conf = new FS::Conf;
192
193   my %info = (
194     %{ skin_info($p) },
195     'phone_login'  => $conf->exists('selfservice_server-phone_login'),
196     'single_domain'=> scalar($conf->config('selfservice_server-single_domain')),
197     'banner_url'       => scalar($conf->config('selfservice-login_banner_url')),
198     'banner_image_md5' => 
199       md5_hex($conf->config_binary('selfservice-login_banner_image')),
200   );
201
202   return \%info;
203
204 }
205
206 sub login_banner_image {
207   my $p = shift;
208   my $conf = new FS::Conf;
209   my $image = $conf->config_binary('selfservice-login_banner_image');
210   return { 
211     'md5'   => md5_hex($image),
212     'image' => $image,
213   };
214 }
215
216 #false laziness w/FS::ClientAPI::passwd::passwd
217 sub login {
218   my $p = shift;
219
220   my $conf = new FS::Conf;
221
222   my $svc_x = '';
223   my $session = {};
224   if ( $p->{'domain'} eq 'svc_phone'
225        && $conf->exists('selfservice_server-phone_login') ) { 
226
227     my $svc_phone = qsearchs( 'svc_phone', { 'phonenum' => $p->{'username'} } );
228     return { error => 'Number not found.' } unless $svc_phone;
229
230     #XXX?
231     #my $pkg_svc = $svc_acct->cust_svc->pkg_svc;
232     #return { error => 'Only primary user may log in.' } 
233     #  if $conf->exists('selfservice_server-primary_only')
234     #    && ( ! $pkg_svc || $pkg_svc->primary_svc ne 'Y' );
235
236     return { error => 'Incorrect PIN.' }
237       unless $svc_phone->check_pin($p->{'password'});
238
239     $svc_x = $svc_phone;
240
241   } elsif ( $p->{email}
242               && (my $contact = FS::contact->by_selfservice_email($p->{email}))
243           )
244   {
245     return { error => 'Incorrect contact password.' }
246       unless $contact->authenticate_password($p->{'password'});
247
248     $session->{'contactnum'} = $contact->contactnum;
249
250     my @cust_contact = grep $_->selfservice_access, $contact->cust_contact;
251     if ( scalar(@cust_contact) == 1 ) {
252       $session->{'custnum'} = $cust_contact[0]->custnum;
253     } elsif ( scalar(@cust_contact) ) {
254       $session->{'customers'} = { map { $_->custnum => $_->cust_main->name }
255                                     @cust_contact
256                                 };
257     } else {
258       return { error => 'No customer self-service access for contact' }; #??
259     }
260
261   } else {
262
263     ( $p->{username}, $p->{domain} ) = split('@', $p->{email}) if $p->{email};
264
265     my $svc_domain = qsearchs('svc_domain', { 'domain' => $p->{'domain'} } )
266       or return { error => 'Domain '. $p->{'domain'}. ' not found' };
267
268     my @svc_acct = qsearch( 'svc_acct', { 'username'  => $p->{'username'},
269                                           'domsvc'    => $svc_domain->svcnum, }
270                           );
271
272     if ( $conf->exists('selfservice_server-login_svcpart') ) {
273       my @svcpart = $conf->config('selfservice_server-login_svcpart');
274       @svc_acct = grep { my $svcpart = $_->cust_svc->svcpart;
275                          scalar( grep( $_ eq $svcpart, @svcpart ) );
276                        }
277                     @svc_acct;
278     }
279
280     if ( $conf->exists('selfservice_server-primary_only') ) {
281         @svc_acct =
282           grep {
283             my $cust_svc = $_->cust_svc;
284             $cust_svc->cust_pkg->part_pkg->svcpart([qw( svc_acct svc_phone )])
285               == $cust_svc->svcpart
286           }
287           @svc_acct;
288     }
289
290     return { error => 'User not found.' } unless @svc_acct;
291
292     return { error => 'Multiple users.' } if scalar(@svc_acct) > 1;
293
294     my $svc_acct = $svc_acct[0];
295
296     if ( $conf->exists('selfservice_server-login_svcpart') ) {
297       my @svcpart = $conf->config('selfservice_server-login_svcpart');
298       my $svcpart = $svc_acct->cust_svc->svcpart;
299       return { error => 'Invalid user.' } 
300         unless grep($_ eq $svcpart, @svcpart);
301     }
302
303     return { error => 'Incorrect password.' }
304       unless $svc_acct->check_password($p->{'password'});
305
306     $svc_x = $svc_acct;
307
308   }
309
310   if ( $svc_x ) {
311
312     $session->{'svcnum'} = $svc_x->svcnum;
313
314     my $cust_svc = $svc_x->cust_svc;
315     my $cust_pkg = $cust_svc->cust_pkg;
316     if ( $cust_pkg ) {
317       my $cust_main = $cust_pkg->cust_main;
318       $session->{'custnum'} = $cust_main->custnum;
319       if ( $conf->exists('pkg-balances') ) {
320         my @cust_pkg = grep { $_->part_pkg->freq !~ /^(0|$)/ }
321                             $cust_main->ncancelled_pkgs;
322         $session->{'pkgnum'} = $cust_pkg->pkgnum
323           if scalar(@cust_pkg) > 1;
324       }
325     }
326
327     #my $pkg_svc = $svc_acct->cust_svc->pkg_svc;
328     #return { error => 'Only primary user may log in.' } 
329     #  if $conf->exists('selfservice_server-primary_only')
330     #    && ( ! $pkg_svc || $pkg_svc->primary_svc ne 'Y' );
331     my $part_pkg = $cust_pkg->part_pkg;
332     return { error => 'Only primary user may log in.' }
333       if $conf->exists('selfservice_server-primary_only')
334          && $cust_svc->svcpart != $part_pkg->svcpart([qw( svc_acct svc_phone )]);
335
336   }
337
338   my $session_id;
339   do {
340     $session_id = sha512_hex(time(). {}. rand(). $$)
341   } until ( ! defined _cache->get($session_id) ); #just in case
342
343   my $timeout = $conf->config('selfservice-session_timeout') || '1 hour';
344   _cache->set( $session_id, $session, $timeout );
345
346   return { 'error'      => '',
347            'session_id' => $session_id,
348            %$session,
349          };
350 }
351
352 sub logout {
353   my $p = shift;
354   my $skin_info = skin_info($p);
355   if ( $p->{'session_id'} ) {
356     _cache->remove($p->{'session_id'});
357     return { %$skin_info, 'error' => '' };
358   } else {
359     return { %$skin_info, 'error' => "Can't resume session" }; #better error message
360   }
361 }
362
363 sub switch_acct {
364   my $p = shift;
365
366   my($context, $session, $custnum) = _custoragent_session_custnum($p);
367   return { 'error' => $session } if $context eq 'error';
368
369   my $svc_acct = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_acct' )
370     or return { 'error' => "Service not found" };
371
372   $session->{'svcnum'} = $svc_acct->svcnum;
373
374   my $conf = new FS::Conf;
375   my $timeout = $conf->config('selfservice-session_timeout') || '1 hour';
376   _cache->set( $p->{'session_id'}, $session, $timeout );
377
378   return { 'error' => '' };
379
380 }
381
382 sub switch_cust {
383   my $p = shift;
384   my($context, $session, $custnum) = _custoragent_session_custnum($p);
385   return { 'error' => $session } if $context eq 'error';
386
387   $session->{'custnum'} = $p->{'custnum'}
388     if exists $session->{'customers'}{ $p->{'custnum'} };
389
390   my $conf = new FS::Conf;
391   my $timeout = $conf->config('selfservice-session_timeout') || '1 hour';
392   _cache->set( $p->{'session_id'}, $session, $timeout );
393
394   return { 'error'      => '',
395            %{ customer_info( { session_id=>$p->{'session_id'} } ) },
396          };
397 }
398
399 sub payment_gateway {
400   # internal use only
401   # takes a cust_main and a cust_payby entry, returns the payment_gateway
402   my $conf = new FS::Conf;
403   my $cust_main = shift;
404   my $cust_payby = shift;
405   my $gatewaynum = $conf->config('selfservice-payment_gateway');
406   if ( $gatewaynum ) {
407     my $pg = qsearchs('payment_gateway', { gatewaynum => $gatewaynum });
408     die "configured gatewaynum $gatewaynum not found!" if !$pg;
409     return $pg;
410   }
411   else {
412     return '' if ! FS::payby->realtime($cust_payby);
413     my $pg = $cust_main->agent->payment_gateway(
414       'method'  => FS::payby->payby2bop($cust_payby),
415       'nofatal' => 1
416     );
417     return $pg;
418   }
419 }
420
421 sub access_info {
422   my $p = shift;
423
424   my $conf = new FS::Conf;
425
426   my $info = skin_info($p);
427
428   use vars qw( $cust_paybys ); #cache for performance
429   unless ( $cust_paybys ) {
430
431     my %cust_paybys = map { $_ => 1 }
432                       map { FS::payby->payby2payment($_) }
433                           $conf->config('signup_server-payby');
434
435     $cust_paybys = [ keys %cust_paybys ];
436
437   }
438   $info->{'cust_paybys'} = $cust_paybys;
439
440   my($context, $session, $custnum) = _custoragent_session_custnum($p);
441   return { 'error' => $session } if $context eq 'error';
442
443   my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } );
444
445   $info->{'hide_payment_fields'} = [ 
446     map { 
447       my $pg = $cust_main && payment_gateway($cust_main, $_);
448       $pg && $pg->gateway_namespace eq 'Business::OnlineThirdPartyPayment';
449     } @{ $info->{cust_paybys} }
450   ];
451
452   $info->{'self_suspend_reason'} = 
453       $conf->config('selfservice-self_suspend_reason',
454                       $cust_main ? $cust_main->agentnum : ''
455                    );
456
457   $info->{'edit_ticket_subject'} =
458       $conf->exists('ticket_system-selfservice_edit_subject') && 
459       $cust_main && $cust_main->edit_subject;
460
461   $info->{'timeout'} = $conf->config('selfservice-timeout') || 3600;
462
463   $info->{'hide_usage'} = $conf->exists('selfservice_hide-usage');
464
465   return { %$info,
466            'custnum'       => $custnum,
467            'access_pkgnum' => $session->{'pkgnum'},
468            'access_svcnum' => $session->{'svcnum'},
469          };
470 }
471
472 sub customer_info {
473   my $p = shift;
474
475   my($context, $session, $custnum) = _custoragent_session_custnum($p);
476   return { 'error' => $session } if $context eq 'error';
477
478   my %return;
479
480   my $conf = new FS::Conf;
481   $return{'require_address2'} = $conf->exists('cust_main-require_address2');
482
483 #  if ( $FS::TicketSystem::system ) {
484 #    warn "$me customer_info: initializing ticket system\n" if $DEBUG;
485 #    FS::TicketSystem->init();
486 #  }
487  
488   if ( $custnum ) { #customer record
489
490     %return = ( %return, %{ customer_info_short($p) } );
491
492     #redundant with customer_info_short, but we need it for several things below
493     my $search = { 'custnum' => $custnum };
494     $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
495     my $cust_main = qsearchs('cust_main', $search )
496       or return { 'error' => "customer_info: unknown custnum $custnum" };
497
498     my $list_tickets = list_tickets($p);
499     $return{'tickets'} = $list_tickets->{'tickets'};
500
501     if ( $session->{'pkgnum'} ) {
502       #XXX open invoices in the pkg-balances case
503     } else {
504       $return{'money_char'} = $conf->config("money_char") || '$';
505       my @open = map {
506                        {
507                          invnum     => $_->invnum,
508                          date       => time2str("%b %o, %Y", $_->_date),
509                          owed       => $_->owed,
510                          charged    => $_->charged,
511                        };
512                      } $cust_main->open_cust_bill;
513       $return{open_invoices} = \@open;
514
515       my $sql = 'SELECT MAX(_date) FROM cust_bill WHERE custnum = ?';
516       my $sth = dbh->prepare($sql) or die  dbh->errstr;
517       $sth->execute($custnum)      or die $sth->errstr;
518       $return{'last_invoice_date'} = $sth->fetchrow_arrayref->[0];
519       $return{'last_invoice_date_pretty'} =
520         time2str('%m/%d/%Y', $return{'last_invoice_date'} );
521     }
522
523     #customer_info_short always has nobalance on..
524     $return{small_custview} =
525       small_custview( $cust_main,
526                       $return{countrydefault},
527                       ( $session->{'pkgnum'} ? 1 : 0 ), #nobalance
528                     );
529
530     $return{has_ship_address} = $cust_main->has_ship_address;
531     $return{status} = $cust_main->status_label; #$cust_main->status; #better to break anyone obscurely testing for strings in self-service than to have to upgrade every front-end to get the new status to display
532     $return{statuscolor} = $cust_main->statuscolor;
533     $return{status_label} = $cust_main->status_label;
534
535     # compatibility: some places in selfservice use this to determine
536     # if there's a ship address
537     if ( $return{has_ship_address} ) {
538       $return{ship_last}  = $cust_main->last;
539       $return{ship_first} = $cust_main->first;
540     }
541
542     if (scalar($conf->config('support_packages'))) {
543       my @support_services = ();
544       foreach ($cust_main->support_services) {
545         my $seconds = $_->svc_x->seconds || 0;
546         my $time_remaining = (($seconds < 0) ? '-' : '' ).
547                              int(abs($seconds)/3600)."h".
548                              sprintf("%02d",(abs($seconds)%3600)/60)."m";
549         my $cust_pkg = $_->cust_pkg;
550         my $pkgnum = '';
551         my $pkg = '';
552         $pkgnum = $cust_pkg->pkgnum if $cust_pkg;
553         $pkg = $cust_pkg->part_pkg->pkg if $cust_pkg;
554         push @support_services, { svcnum => $_->svcnum,
555                                   time => $time_remaining,
556                                   pkgnum => $pkgnum,
557                                   pkg => $pkg,
558                                 };
559       }
560       $return{support_services} = \@support_services;
561     }
562
563     if ( $conf->config('prepayment_discounts-credit_type') ) {
564       #need to eval?
565       $return{discount_terms_hash} = { $cust_main->discount_terms_hash };
566     }
567
568   } elsif ( $session->{'svcnum'} ) { #no customer record
569
570     my $svc_acct = qsearchs('svc_acct', { 'svcnum' => $session->{'svcnum'} } )
571       or die "unknown svcnum";
572     $return{name} = $svc_acct->email;
573
574   } else {
575
576     return { 'error' => 'Expired session' }; #XXX redirect to login w/this err!
577
578   }
579
580   return { 'error'   => '',
581            'custnum' => $custnum,
582            %return,
583          };
584
585 }
586
587 sub customer_info_short {
588   my $p = shift;
589
590   my($context, $session, $custnum) = _custoragent_session_custnum($p);
591   return { 'error' => $session } if $context eq 'error';
592
593   my %return;
594
595   my $conf = new FS::Conf;
596
597   if ( $custnum ) { #customer record
598
599     my $search = { 'custnum' => $custnum };
600     $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
601     my $cust_main = qsearchs('cust_main', $search )
602       or return { 'error' => "customer_info_short: unknown custnum $custnum" };
603
604     $return{display_custnum} = $cust_main->display_custnum;
605
606     if ( $session->{'pkgnum'} ) { 
607       $return{balance} = $cust_main->balance_pkgnum( $session->{'pkgnum'} );
608       #next_bill_date from cust_pkg?
609     } else {
610       $return{balance} = $cust_main->balance;
611       $return{next_bill_date} = $cust_main->next_bill_date;
612       $return{next_bill_date_pretty} =
613         $return{next_bill_date} ? time2str('%m/%d/%Y', $return{next_bill_date} )
614                                 : '(none)';
615     }
616     $return{balance_pretty} = money_pretty($return{balance});
617
618     $return{countrydefault} = scalar($conf->config('countrydefault'));
619
620     $return{small_custview} =
621       small_custview( $cust_main,
622                       $return{countrydefault},
623                       1, ##nobalance
624                     );
625
626     $return{first}  = $cust_main->first;
627     $return{'last'} = $cust_main->get('last');
628     $return{name}   = $cust_main->first. ' '. $cust_main->get('last');
629
630     $return{payby} = $cust_main->payby;
631
632     #none of these are terribly expensive if we want 'em...
633     for (@cust_main_editable_fields) {
634       $return{$_} = $cust_main->get($_);
635     }
636     #maybe a little more expensive, but it should be cached by now
637     for (@location_editable_fields) {
638       $return{$_} = $cust_main->bill_location->get($_)
639         if $cust_main->bill_locationnum;
640       $return{'ship_'.$_} = $cust_main->ship_location->get($_)
641         if $cust_main->ship_locationnum;
642     }
643  
644     if ( $cust_main->payby =~ /^(CARD|DCRD)$/ ) {
645       $return{payinfo} = $cust_main->paymask;
646       @return{'month', 'year'} = $cust_main->paydate_monthyear;
647     }
648     
649     my @invoicing_list = $cust_main->invoicing_list;
650     $return{'invoicing_list'} =
651       join(', ', grep { $_ !~ /^(POST|FAX)$/ } @invoicing_list );
652     $return{'postal_invoicing'} =
653       0 < ( grep { $_ eq 'POST' } @invoicing_list );
654
655     if ( $session->{'svcnum'} ) {
656       my $cust_svc = qsearchs('cust_svc', { 'svcnum' => $session->{'svcnum'} });
657       $return{'svc_label'} = ($cust_svc->label)[1] if $cust_svc;
658       $return{'svcnum'} = $session->{'svcnum'};
659     }
660
661   } elsif ( $session->{'svcnum'} ) { #no customer record
662
663     #uuh, not supproted yet... die?
664     return { 'error' => 'customer_info_short not yet supported as agent' };
665
666   } else {
667
668     return { 'error' => 'Expired session' }; #XXX redirect to login w/this err!
669
670   }
671
672   # this is here because this routine is called by both fs_ and ng_ main pages, where it appears
673   # it is not customer-specific, though it is only shown to authenticated customers
674   # it is not currently agent-specific, though at some point it might be
675   $return{'announcement'} = join(' ',$conf->config('selfservice-announcement')) || '';
676
677   return { 'error'          => '',
678            'custnum'        => $custnum,
679            %return,
680          };
681 }
682
683 sub billing_history {
684   my $p = shift;
685
686   my($context, $session, $custnum) = _custoragent_session_custnum($p);
687   return { 'error' => $session } if $context eq 'error';
688
689   return { 'error' => 'No customer' } unless $custnum;
690
691   my $search = { 'custnum' => $custnum };
692   $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
693   my $cust_main = qsearchs('cust_main', $search )
694     or return { 'error' => "unknown custnum $custnum" };
695
696   my %return = ();
697
698   if ( $session->{'pkgnum'} ) { 
699     #$return{balance} = $cust_main->balance_pkgnum( $session->{'pkgnum'} );
700     #next_bill_date from cust_pkg?
701     return { 'error' => 'No history for package' };
702   }
703
704   $return{balance} = $cust_main->balance;
705   $return{balance_pretty} = money_pretty($return{balance});
706   $return{next_bill_date} = $cust_main->next_bill_date;
707   $return{next_bill_date_pretty} =
708     $return{next_bill_date} ? time2str('%m/%d/%Y', $return{next_bill_date} )
709                             : '(none)';
710
711   my $conf = new FS::Conf;
712
713   $return{'history'} = [
714     $cust_main->payment_history(
715       'line_items' => $conf->exists('selfservice-billing_history-line_items'),
716       'reverse_sort' => 1,
717     )
718   ];
719
720   $return{'money_char'} = $conf->config("money_char") || '$',
721
722   return \%return;
723
724 }
725
726 sub edit_info {
727   my $p = shift;
728   my $session = _cache->get($p->{'session_id'})
729     or return { 'error' => "Can't resume session" }; #better error message
730
731   my $custnum = $session->{'custnum'}
732     or return { 'error' => "no customer record" };
733
734   my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
735     or return { 'error' => "unknown custnum $custnum" };
736
737   my $new = new FS::cust_main { $cust_main->hash };
738
739   $new->set( $_ => $p->{$_} )
740     foreach grep { exists $p->{$_} } @cust_main_editable_fields;
741
742   if ( exists($p->{address1}) ) {
743     my $bill_location = FS::cust_location->new({
744         map { $_ => $p->{$_} } @location_editable_fields
745     });
746     # if this is unchanged from before, cust_main::replace will ignore it
747     $new->set('bill_location' => $bill_location);
748   }
749
750   if ( exists($p->{ship_address1}) ) {
751     my $ship_location = FS::cust_location->new({
752         map { $_ => $p->{"ship_$_"} } @location_editable_fields
753     });
754     if ( !grep { length($p->{"ship_$_"}) } @location_editable_fields ) {
755       # Selfservice unfortunately tries to indicate "same as billing 
756       # address" by sending all fields empty.  Did this ever work?
757       $ship_location = $cust_main->bill_location;
758     }
759     $new->set('ship_location' => $ship_location);
760   }
761   # but if it hasn't been passed in at all, leave ship_location alone--
762   # DON'T change it to match bill_location.
763
764   my $payby = '';
765   if (exists($p->{'payby'})) {
766     $p->{'payby'} =~ /^([A-Z]{4})$/
767       or return { 'error' => "illegal_payby " . $p->{'payby'} };
768     $payby = $1;
769   }
770
771   my $conf = new FS::Conf;
772
773   if ( $payby =~ /^(CARD|DCRD)$/ ) {
774
775     $new->paydate($p->{'year'}. '-'. $p->{'month'}. '-01');
776
777     if ( $new->payinfo eq $cust_main->paymask ) {
778       $new->payinfo($cust_main->payinfo);
779       $new->paycvv( $p->{'paycvv'} || $cust_main->paycvv );
780     } else {
781       $new->payinfo($p->{'payinfo'});
782       return { 'error' => 'CVV2 is required' }
783         if ! $p->{'paycvv'} && $conf->exists('selfservice-onfile_require_cvv');
784       $new->paycvv( $p->{'paycvv'} )
785     }
786
787     $new->set( 'payby' => $p->{'auto'} ? 'CARD' : 'DCRD' );
788
789   } elsif ( $payby =~ /^(CHEK|DCHK)$/ ) {
790
791     my $payinfo;
792     $p->{'payinfo1'} =~ /^([\dx]+)$/
793       or return { 'error' => "illegal account number ". $p->{'payinfo1'} };
794     my $payinfo1 = $1;
795      $p->{'payinfo2'} =~ /^([\dx\.]+)$/ # . turned on by echeck-country CA ?
796       or return { 'error' => "illegal ABA/routing number ". $p->{'payinfo2'} };
797     my $payinfo2 = $1;
798     $payinfo = $payinfo1. '@'. $payinfo2;
799
800     $new->payinfo( ($payinfo eq $cust_main->paymask)
801                      ? $cust_main->payinfo
802                      : $payinfo
803                  );
804
805     $new->set( 'payby' => $p->{'auto'} ? 'CHEK' : 'DCHK' );
806
807   } elsif ( $payby =~ /^(BILL)$/ ) {
808     #no-op
809   } elsif ( $payby ) {  #notyet ready
810     return { 'error' => "unknown payby $payby" };
811   }
812
813   my @invoicing_list;
814   if ( exists $p->{'invoicing_list'} || exists $p->{'postal_invoicing'} ) {
815     #false laziness with httemplate/edit/process/cust_main.cgi
816     @invoicing_list = split( /\s*\,\s*/, $p->{'invoicing_list'} );
817     push @invoicing_list, 'POST' if $p->{'postal_invoicing'};
818   } else {
819     @invoicing_list = $cust_main->invoicing_list;
820   }
821
822   my $error = $new->replace($cust_main, \@invoicing_list);
823   return { 'error' => $error } if $error;
824   #$cust_main = $new;
825   
826   return { 'error' => '' };
827 }
828
829 sub payment_info {
830   my $p = shift;
831   my $session = _cache->get($p->{'session_id'})
832     or return { 'error' => "Can't resume session" }; #better error message
833
834   ##
835   #generic
836   ##
837
838   my $conf = new FS::Conf;
839   use vars qw($payment_info); #cache for performance
840   unless ( $payment_info ) {
841
842     my %states = map { $_->state => 1 }
843                    qsearch('cust_main_county', {
844                      'country' => $conf->config('countrydefault') || 'US'
845                    } );
846
847     my %cust_paybys = map { $_ => 1 }
848                       map { FS::payby->payby2payment($_) }
849                           $conf->config('signup_server-payby');
850
851     my @cust_paybys = keys %cust_paybys;
852
853     $payment_info = {
854
855       #list all counties/states/countries
856       'cust_main_county' => 
857         [ map { $_->hashref } qsearch('cust_main_county', {}) ],
858
859       #shortcut for one-country folks
860       'states' =>
861         [ sort { $a cmp $b } keys %states ],
862
863       'card_types' => card_types(),
864
865       'withcvv'            => $conf->exists('selfservice-require_cvv'), #or enable optional cvv?
866       'require_cvv'        => $conf->exists('selfservice-require_cvv'),
867       'onfile_require_cvv' => $conf->exists('selfservice-onfile_require_cvv'),
868
869       'paytypes' => [ FS::cust_payby::paytypes ],
870
871       'paybys' => [ $conf->config('signup_server-payby') ],
872       'cust_paybys' => \@cust_paybys,
873
874       'stateid_label' => FS::Msgcat::_gettext('stateid'),
875       'stateid_state_label' => FS::Msgcat::_gettext('stateid_state'),
876
877       'show_ss'  => $conf->exists('show_ss'),
878       'show_stateid' => $conf->exists('show_stateid'),
879       'show_paystate' => $conf->exists('show_bankstate'),
880
881       'save_unchecked' => $conf->exists('selfservice-save_unchecked'),
882
883       'credit_card_surcharge_percentage' => scalar($conf->config('credit-card-surcharge-percentage')),
884     };
885
886   }
887
888   ##
889   #customer-specific
890   ##
891
892   my %return = %$payment_info;
893
894   my $custnum = $session->{'custnum'};
895
896   my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
897     or return { 'error' => "unknown custnum $custnum" };
898
899   $return{'hide_payment_fields'} = [
900     map { 
901       my $pg = payment_gateway($cust_main, $_);
902       $pg && $pg->gateway_namespace eq 'Business::OnlineThirdPartyPayment';
903     } @{ $return{cust_paybys} }
904   ];
905
906   $return{balance} = $cust_main->balance; #XXX pkg-balances?
907
908   $return{payname} = $cust_main->payname
909                      || ( $cust_main->first. ' '. $cust_main->get('last') );
910
911   $return{$_} = $cust_main->bill_location->get($_) 
912     for qw(address1 address2 city state zip);
913
914   $return{payby} = $cust_main->payby;
915   $return{stateid_state} = $cust_main->stateid_state;
916
917   if ( $cust_main->payby =~ /^(CARD|DCRD)$/ ) {
918     $return{card_type} = cardtype($cust_main->payinfo);
919     $return{payinfo} = $cust_main->paymask;
920
921     @return{'month', 'year'} = $cust_main->paydate_monthyear;
922
923   }
924
925   if ( $cust_main->payby =~ /^(CHEK|DCHK)$/ ) {
926     my ($payinfo1, $payinfo2) = split '@', $cust_main->paymask;
927     $return{payinfo1} = $payinfo1;
928     $return{payinfo2} = $payinfo2;
929     $return{paytype}  = $cust_main->paytype;
930     $return{paystate} = $cust_main->paystate;
931     $return{payname}  = $cust_main->payname;    # override 'first/last name' default from above, if any.  Is instution-name here.  (#15819)
932   }
933
934   if ( $conf->config('prepayment_discounts-credit_type') ) {
935     #need to eval?
936     $return{discount_terms_hash} = { $cust_main->discount_terms_hash };
937   }
938
939   #doubleclick protection
940   my $_date = time;
941   $return{payunique} = "webui-MyAccount-$_date-$$-". rand() * 2**32; #new
942   $return{paybatch} = $return{payunique};  #back compat
943
944   return { 'error' => '',
945            %return,
946          };
947
948 }
949
950 #some false laziness with httemplate/process/payment.cgi - look there for
951 #ACH and CVV support stuff
952
953 sub validate_payment {
954   my $p = shift;
955
956   my $session = _cache->get($p->{'session_id'})
957     or return { 'error' => "Can't resume session" }; #better error message
958
959   my $custnum = $session->{'custnum'};
960
961   my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
962     or return { 'error' => "unknown custnum $custnum" };
963
964   $p->{'amount'} =~ /^\s*(\d+(\.\d{2})?)\s*$/
965     or return { 'error' => gettext('illegal_amount') };
966   my $amount = $1;
967   return { error => 'Amount must be greater than 0' } unless $amount > 0;
968
969   #false laziness w/tr-amount_fee.html, but we don't want selfservice users
970   #changing the hidden form values
971   my $conf = new FS::Conf;
972   my $fee_display = $conf->config('selfservice_process-display') || 'add';
973   my $fee_pkgpart = $conf->config('selfservice_process-pkgpart', $cust_main->agentnum);
974   my $fee_skip_first = $conf->exists('selfservice_process-skip_first');
975   if ( $fee_display eq 'add'
976          and $fee_pkgpart
977          and ! $fee_skip_first || scalar($cust_main->cust_pay)
978      )
979   {
980     my $fee_pkg = qsearchs('part_pkg', { pkgpart=>$fee_pkgpart } );
981     $amount = sprintf('%.2f', $amount + $fee_pkg->option('setup_fee') );
982   }
983
984   $p->{'discount_term'} =~ /^\s*(\d*)\s*$/
985     or return { 'error' => gettext('illegal_discount_term'). ': '. $p->{'discount_term'} };
986   my $discount_term = $1;
987
988   $p->{'payname'} =~ /^([\w \,\.\-\']+)$/
989     or return { 'error' => gettext('illegal_name'). " payname: ". $p->{'payname'} };
990   my $payname = $1;
991
992   $p->{'payunique'} =~ /^([\w \!\@\#\$\%\&\(\)\-\+\;\:\'\"\,\.\?\/\=]*)$/
993     or return { 'error' => gettext('illegal_text'). " payunique: ". $p->{'payunique'} };
994   my $payunique = $1;
995
996   $p->{'paybatch'} =~ /^([\w \!\@\#\$\%\&\(\)\-\+\;\:\'\"\,\.\?\/\=]*)$/
997     or return { 'error' => gettext('illegal_text'). " paybatch: ". $p->{'paybatch'} };
998   my $paybatch = $1;
999
1000   $payunique = $paybatch if ! length($payunique) && length($paybatch);
1001
1002   $p->{'payby'} ||= 'CARD';
1003   $p->{'payby'} =~ /^([A-Z]{4})$/
1004     or return { 'error' => "illegal_payby " . $p->{'payby'} };
1005   my $payby = $1;
1006
1007   #false laziness w/process/payment.cgi
1008   my $payinfo;
1009   my $paycvv = '';
1010   if ( $payby eq 'CHEK' || $payby eq 'DCHK' ) {
1011   
1012     $p->{'payinfo1'} =~ /^([\dx]+)$/
1013       or return { 'error' => "illegal account number ". $p->{'payinfo1'} };
1014     my $payinfo1 = $1;
1015      $p->{'payinfo2'} =~ /^([\dx]+)$/
1016       or return { 'error' => "illegal ABA/routing number ". $p->{'payinfo2'} };
1017     my $payinfo2 = $1;
1018     $payinfo = $payinfo1. '@'. $payinfo2;
1019
1020     $payinfo = $cust_main->payinfo
1021       if $cust_main->paymask eq $payinfo;
1022    
1023   } elsif ( $payby eq 'CARD' || $payby eq 'DCRD' ) {
1024    
1025     $payinfo = $p->{'payinfo'};
1026
1027     my $onfile = 0;
1028
1029     #more intelligent matching will be needed here if you change
1030     #card_masking_method and don't remove existing paymasks
1031     if ( $cust_main->paymask eq $payinfo ) {
1032       $payinfo = $cust_main->payinfo;
1033       $onfile = 1;
1034     }
1035
1036     $payinfo =~ s/\D//g;
1037     $payinfo =~ /^(\d{13,16}|\d{8,9})$/
1038       or return { 'error' => gettext('invalid_card') }; # . ": ". $self->payinfo
1039     $payinfo = $1;
1040
1041     validate($payinfo)
1042       or return { 'error' => gettext('invalid_card') }; # . ": ". $self->payinfo
1043     return { 'error' => gettext('unknown_card_type') }
1044       if $payinfo !~ /^99\d{14}$/ && cardtype($payinfo) eq "Unknown";
1045
1046     if ( length($p->{'paycvv'}) && $p->{'paycvv'} !~ /^\s*$/ ) {
1047       if ( cardtype($payinfo) eq 'American Express card' ) {
1048         $p->{'paycvv'} =~ /^\s*(\d{4})\s*$/
1049           or return { 'error' => "CVV2 (CID) for American Express cards is four digits." };
1050         $paycvv = $1;
1051       } else {
1052         $p->{'paycvv'} =~ /^\s*(\d{3})\s*$/
1053           or return { 'error' => "CVV2 (CVC2/CID) is three digits." };
1054         $paycvv = $1;
1055       }
1056     } elsif ( $conf->exists('selfservice-onfile_require_cvv') ) {
1057       return { 'error' => 'CVV2 is required' };
1058     } elsif ( !$onfile && $conf->exists('selfservice-require_cvv') ) {
1059       return { 'error' => 'CVV2 is required' };
1060     }
1061   
1062   } else {
1063     die "unknown payby $payby";
1064   }
1065
1066   my %payby2fields = (
1067     'CARD' => [ qw( paystart_month paystart_year payissue payip
1068                     address1 address2 city state zip country    ) ],
1069     'CHEK' => [ qw( ss paytype paystate stateid stateid_state payip ) ],
1070   );
1071
1072   my $card_type = '';
1073   $card_type = cardtype($payinfo) if $payby eq 'CARD';
1074
1075   { 
1076     'cust_main'      => $cust_main, #XXX or just custnum??
1077     'amount'         => sprintf('%.2f', $amount),
1078     'payby'          => $payby,
1079     'payinfo'        => $payinfo,
1080     'paymask'        => $cust_main->mask_payinfo( $payby, $payinfo ),
1081     'card_type'      => $card_type,
1082     'paydate'        => $p->{'year'}. '-'. $p->{'month'}. '-01',
1083     'paydate_pretty' => $p->{'month'}. ' / '. $p->{'year'},
1084     'month'          => $p->{'month'},
1085     'year'           => $p->{'year'},
1086     'payname'        => $payname,
1087     'payunique'      => $payunique,
1088     'paybatch'       => $paybatch,
1089     'paycvv'         => $paycvv,
1090     'payname'        => $payname,
1091     'discount_term'  => $discount_term,
1092     'pkgnum'         => $session->{'pkgnum'},
1093     map { $_ => $p->{$_} } ( @{ $payby2fields{$payby} },
1094                              qw( save auto ),
1095                            )
1096   };
1097
1098 }
1099
1100 sub store_payment {
1101   my $p = shift;
1102
1103   my $validate = validate_payment($p);
1104   return $validate if $validate->{'error'};
1105
1106   my $conf = new FS::Conf;
1107   my $timeout = $conf->config('selfservice-session_timeout') || '1 hour'; #?
1108   _cache->set( 'payment_'.$p->{'session_id'}, $validate, $timeout );
1109
1110   +{ map { $_=>$validate->{$_} }
1111       qw( card_type paymask payname paydate_pretty month year amount
1112           address1 address2 city state zip country
1113         )
1114   };
1115
1116 }
1117
1118 sub process_stored_payment {
1119   my $p = shift;
1120
1121   my $session_id = $p->{'session_id'};
1122
1123   my $payment_info = _cache->get( "payment_$session_id" )
1124     or return { 'error' => "Can't resume session" }; #better error message
1125
1126   do_process_payment($payment_info);
1127
1128 }
1129
1130 sub process_payment {
1131   my $p = shift;
1132
1133   my $payment_info = validate_payment($p);
1134   return $payment_info if $payment_info->{'error'};
1135
1136   do_process_payment($payment_info);
1137
1138 }
1139
1140 sub do_process_payment {
1141   my $validate = shift;
1142
1143   my $cust_main = $validate->{'cust_main'};
1144
1145   my $amount = delete $validate->{'amount'};
1146   my $paynum = '';
1147
1148   my $payby = delete $validate->{'payby'};
1149
1150   if ( $validate->{'save'} ) {
1151     my $new = new FS::cust_main { $cust_main->hash };
1152     if ($payby eq 'CARD' || $payby eq 'DCRD') {
1153       $new->set( $_ => $validate->{$_} )
1154         foreach qw( payname paystart_month paystart_year payissue payip );
1155       $new->set( 'payby' => $validate->{'auto'} ? 'CARD' : 'DCRD' );
1156
1157       my $bill_location = FS::cust_location->new({
1158           map { $_ => $validate->{$_} } 
1159           qw(address1 address2 city state country zip)
1160       }); # county?
1161       $new->set('bill_location' => $bill_location);
1162       # but don't allow the service address to change this way.
1163
1164     } elsif ($payby eq 'CHEK' || $payby eq 'DCHK') {
1165       $new->set( $_ => $validate->{$_} )
1166         foreach qw( payname payip paytype paystate
1167                     stateid stateid_state );
1168       $new->set( 'payby' => $validate->{'auto'} ? 'CHEK' : 'DCHK' );
1169     }
1170     $new->payinfo( $validate->{'payinfo'} ); #to properly set paymask
1171     $new->set( 'paydate' => $validate->{'paydate'} );
1172     my $error = $new->replace($cust_main);
1173     if ( $error ) {
1174       #no, this causes customers to process their payments again
1175       #return { 'error' => $error };
1176       #XXX just warn verosely for now so i can figure out how these happen in
1177       # the first place, eventually should redirect them to the "change
1178       #address" page but indicate if the payment processed?
1179       delete($validate->{'payinfo'}); #don't want to log this!
1180       warn "WARNING: error changing customer info when processing payment (not returning to customer as a processing error): $error\n".
1181            "NEW: ". Dumper($new)."\n".
1182            "OLD: ". Dumper($cust_main)."\n".
1183            "PACKET: ". Dumper($validate)."\n";
1184     } else {
1185       $cust_main = $new;
1186     }
1187   }
1188
1189   my $error = $cust_main->realtime_bop( $FS::payby::payby2bop{$payby}, $amount,
1190     'quiet'       => 1,
1191     'manual'      => 1,
1192     'selfservice' => 1,
1193     'paynum_ref'  => \$paynum,
1194     %$validate,
1195   );
1196   return { 'error' => $error } if $error;
1197
1198   #no error, so order the fee package if applicable...
1199   my $conf = new FS::Conf;
1200   my $fee_pkgpart = $conf->config('selfservice_process-pkgpart', $cust_main->agentnum);
1201   my $fee_skip_first = $conf->exists('selfservice_process-skip_first');
1202   
1203   if ( $fee_pkgpart and ! $fee_skip_first || scalar($cust_main->cust_pay) ) {
1204
1205     my $cust_pkg = new FS::cust_pkg { 'pkgpart' => $fee_pkgpart };
1206
1207     $error = $cust_main->order_pkg( 'cust_pkg' => $cust_pkg );
1208     return { 'error' => "payment processed successfully, but error ordering fee: $error" }
1209       if $error;
1210
1211     #and generate an invoice for it now too
1212     $error = $cust_main->bill( 'pkg_list' => [ $cust_pkg ] );
1213     return { 'error' => "payment processed and fee ordered sucessfully, but error billing fee: $error" }
1214       if $error;
1215
1216   }
1217
1218   $cust_main->apply_payments;
1219
1220   my $cust_pay = '';
1221   my $receipt_html = '';
1222   if ($paynum) {
1223       # currently supported for realtime CC only; send receipt data to SS
1224       $cust_pay = qsearchs('cust_pay', { 'paynum' => $paynum } );
1225       if($cust_pay) {
1226         $receipt_html = qq!
1227 <TABLE BGCOLOR="#cccccc" BORDER=0 CELLSPACING=2>
1228
1229 <TR>
1230   <TD ALIGN="right">Payment#</TD>
1231   <TD BGCOLOR="#FFFFFF"><B>! . $cust_pay->paynum . qq!</B></TD>
1232 </TR>
1233
1234 <TR>
1235   <TD ALIGN="right">Date</TD>
1236
1237   <TD BGCOLOR="#FFFFFF"><B>! . 
1238         time2str("%a&nbsp;%b&nbsp;%o,&nbsp;%Y&nbsp;%r", $cust_pay->_date)
1239                                                             . qq!</B></TD>
1240 </TR>
1241
1242
1243 <TR>
1244   <TD ALIGN="right">Amount</TD>
1245   <TD BGCOLOR="#FFFFFF"><B>! . sprintf('%.2f', $cust_pay->paid) . qq!</B></TD>
1246
1247 </TR>
1248
1249 <TR>
1250   <TD ALIGN="right">Payment method</TD>
1251   <TD BGCOLOR="#FFFFFF"><B>! . $cust_pay->payby_name .' #'. $cust_pay->paymask
1252                                                                 . qq!</B></TD>
1253 </TR>
1254
1255 </TABLE>
1256 !;
1257       }
1258   }
1259
1260   if ( $cust_pay ) {
1261
1262     return {
1263       'error'        => '',
1264       'amount'       => sprintf('%.2f', $cust_pay->paid),
1265       'date'         => $cust_pay->_date,
1266       'date_pretty'  => time2str('%Y-%m-%d', $cust_pay->_date),
1267       'time_pretty'  => time2str('%T', $cust_pay->_date),
1268       'auth_num'     => $cust_pay->auth,
1269       'order_num'    => $cust_pay->order_number,
1270       'receipt_html' => $receipt_html,
1271     };
1272
1273   } else {
1274
1275     return {
1276       'error'        => '',
1277       'receipt_html' => '',
1278     };
1279
1280   }
1281
1282 }
1283
1284 sub realtime_collect {
1285   my $p = shift;
1286
1287   my $session = _cache->get($p->{'session_id'})
1288     or return { 'error' => "Can't resume session" }; #better error message
1289
1290   my $custnum = $session->{'custnum'};
1291
1292   my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1293     or return { 'error' => "unknown custnum $custnum" };
1294
1295   my $amount;
1296   if ( $p->{'amount'} ) {
1297     $amount = $p->{'amount'};
1298   }
1299   elsif ( $session->{'pkgnum'} ) {
1300     $amount = $cust_main->balance_pkgnum( $session->{'pkgnum'} );
1301   }
1302   else {
1303     $amount = $cust_main->balance;
1304   }
1305
1306   my $error = $cust_main->realtime_collect(
1307     'method'     => $p->{'method'},
1308     'amount'     => $amount,
1309     'pkgnum'     => $session->{'pkgnum'},
1310     'session_id' => $p->{'session_id'},
1311     'apply'      => 1,
1312     'selfservice'=> 1,
1313   );
1314   return { 'error' => $error } unless ref( $error );
1315
1316   return { 'error' => '', amount => $amount, %$error };
1317 }
1318
1319 sub start_thirdparty {
1320   my $p = shift;
1321   my $session = _cache->get($p->{'session_id'})
1322     or return { 'error' => "Can't resume session" }; #better error message
1323   my $custnum = $session->{'custnum'};
1324   my $cust_main = FS::cust_main->by_key($custnum);
1325   
1326   my $amount = $p->{'amount'}
1327     or return { error => 'no amount' };
1328
1329   my $result = $cust_main->create_payment(
1330     'method'      => $p->{'method'},
1331     'amount'      => $p->{'amount'},
1332     'pkgnum'      => $session->{'pkgnum'},
1333     'session_id'  => $p->{'session_id'},
1334   );
1335   
1336   if ( ref($result) ) { # hashref or error
1337     return $result;
1338   } else {
1339     return { error => $result };
1340   }
1341 }
1342
1343 sub finish_thirdparty {
1344   my $p = shift;
1345   my $session_id = delete $p->{'session_id'};
1346   my $session = _cache->get($session_id)
1347     or return { 'error' => "Can't resume session" };
1348   my $custnum = $session->{'custnum'};
1349   my $cust_main = FS::cust_main->by_key($custnum);
1350
1351   if ( $p->{_cancel} ) {
1352     # customer backed out of making a payment
1353     return $cust_main->cancel_payment( $session_id );
1354   }
1355   my $result = $cust_main->execute_payment( $session_id, %$p );
1356   if ( ref($result) ) {
1357     return $result;
1358   } else {
1359     return { error => $result };
1360   }
1361 }
1362
1363 sub process_payment_order_pkg {
1364   my $p = shift;
1365
1366   my $hr = process_payment($p);
1367   return $hr if $hr->{'error'};
1368
1369   order_pkg($p);
1370 }
1371
1372 sub process_payment_order_renew {
1373   my $p = shift;
1374
1375   my $hr = process_payment($p);
1376   return $hr if $hr->{'error'};
1377
1378   order_renew($p);
1379 }
1380
1381 sub process_prepay {
1382
1383   my $p = shift;
1384
1385   my $session = _cache->get($p->{'session_id'})
1386     or return { 'error' => "Can't resume session" }; #better error message
1387
1388   my %return;
1389
1390   my $custnum = $session->{'custnum'};
1391
1392   my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1393     or return { 'error' => "unknown custnum $custnum" };
1394
1395   my( $amount, $seconds, $upbytes, $downbytes, $totalbytes ) = ( 0, 0, 0, 0, 0 );
1396   my $error = $cust_main->recharge_prepay( $p->{'prepaid_cardnum'},
1397                                            \$amount,
1398                                            \$seconds,
1399                                            \$upbytes,
1400                                            \$downbytes,
1401                                            \$totalbytes,
1402                                          );
1403
1404   return { 'error' => $error } if $error;
1405
1406   return { 'error'     => '',
1407            'amount'    => $amount,
1408            'seconds'   => $seconds,
1409            'duration'  => duration_exact($seconds),
1410            'upbytes'   => $upbytes,
1411            'upload'    => FS::UI::bytecount::bytecount_unexact($upbytes),
1412            'downbytes' => $downbytes,
1413            'download'  => FS::UI::bytecount::bytecount_unexact($downbytes),
1414            'totalbytes'=> $totalbytes,
1415            'totalload' => FS::UI::bytecount::bytecount_unexact($totalbytes),
1416          };
1417
1418 }
1419
1420 sub invoice {
1421   my $p = shift;
1422   my $session = _cache->get($p->{'session_id'})
1423     or return { 'error' => "Can't resume session" }; #better error message
1424
1425   my $custnum = $session->{'custnum'};
1426
1427   my $invnum = $p->{'invnum'};
1428
1429   my $cust_bill = qsearchs('cust_bill', { 'invnum'  => $invnum,
1430                                           'custnum' => $custnum } )
1431     or return { 'error' => "Can't find invnum" };
1432
1433   #my %return;
1434
1435   return { 'error'        => '',
1436            'invnum'       => $invnum,
1437            'invoice_text' => join('', $cust_bill->print_text ),
1438            'invoice_html' => $cust_bill->print_html( { unsquelch_cdr => 1 } ),
1439          };
1440
1441 }
1442
1443 sub invoice_pdf {
1444   my $p = shift;
1445   my $session = _cache->get($p->{'session_id'})
1446     or return { 'error' => "Can't resume session" }; #better error message
1447
1448   my $custnum = $session->{'custnum'};
1449
1450   my $invnum = $p->{'invnum'};
1451
1452   my $cust_bill = qsearchs('cust_bill', { 'invnum'  => $invnum,
1453                                           'custnum' => $custnum } )
1454     or return { 'error' => "Can't find invnum" };
1455
1456   #my %return;
1457
1458   return { 'error'       => '',
1459            'invnum'      => $invnum,
1460            'invoice_pdf' => $cust_bill->print_pdf({
1461                               'unsquelch_cdr' => 1,
1462                               'locale'        => $p->{'locale'},
1463                             }),
1464          };
1465
1466 }
1467
1468 sub legacy_invoice {
1469   my $p = shift;
1470   my $session = _cache->get($p->{'session_id'})
1471     or return { 'error' => "Can't resume session" }; #better error message
1472
1473   my $custnum = $session->{'custnum'};
1474
1475   my $legacyinvnum = $p->{'legacyinvnum'};
1476
1477   my %hash = (
1478     'legacyinvnum' => $legacyinvnum,
1479     'custnum'      => $custnum,
1480   );
1481
1482   my $legacy_cust_bill =
1483          qsearchs('legacy_cust_bill', { %hash, 'locale' => $p->{'locale'} } )
1484       || qsearchs('legacy_cust_bill', \%hash )
1485     or return { 'error' => "Can't find legacyinvnum" };
1486
1487   #my %return;
1488
1489   return { 'error'        => '',
1490            'legacyinvnum' => $legacyinvnum,
1491            'legacyid'     => $legacy_cust_bill->legacyid,
1492            'invoice_html' => $legacy_cust_bill->content_html,
1493          };
1494
1495 }
1496
1497 sub legacy_invoice_pdf {
1498   my $p = shift;
1499   my $session = _cache->get($p->{'session_id'})
1500     or return { 'error' => "Can't resume session" }; #better error message
1501
1502   my $custnum = $session->{'custnum'};
1503
1504   my $legacyinvnum = $p->{'legacyinvnum'};
1505
1506   my $legacy_cust_bill = qsearchs('legacy_cust_bill', {
1507     'legacyinvnum' => $legacyinvnum,
1508     'custnum'      => $custnum,
1509   }) or return { 'error' => "Can't find legacyinvnum" };
1510
1511   #my %return;
1512
1513   return { 'error'        => '',
1514            'legacyinvnum' => $legacyinvnum,
1515            'legacyid'     => $legacy_cust_bill->legacyid,
1516            'invoice_pdf'  => $legacy_cust_bill->content_pdf,
1517          };
1518
1519 }
1520
1521 sub invoice_logo {
1522   my $p = shift;
1523
1524   #sessioning for this?  how do we get the session id to the backend invoice
1525   # template so it can add it to the link, blah
1526
1527   my $agentnum = '';
1528   if ( $p->{'invnum'} ) {
1529     my $cust_bill = qsearchs('cust_bill', { 'invnum' => $p->{'invnum'} } )
1530       or return { 'error' => 'unknown invnum' };
1531     $agentnum = $cust_bill->cust_main->agentnum;
1532   }
1533
1534   my $templatename = $p->{'template'} || $p->{'templatename'};
1535
1536   #false laziness-ish w/view/cust_bill-logo.cgi
1537
1538   my $conf = new FS::Conf;
1539   if ( $templatename =~ /^([^\.\/]*)$/ && $conf->exists("logo_$1.png") ) {
1540     $templatename = "_$1";
1541   } else {
1542     $templatename = '';
1543   }
1544
1545   my $filename = "logo$templatename.png";
1546
1547   return { 'error'        => '',
1548            'logo'         => $conf->config_binary($filename, $agentnum),
1549            'content_type' => 'image/png', #should allow gif, jpg too
1550          };
1551 }
1552
1553
1554 sub list_invoices {
1555   my $p = shift;
1556   my $session = _cache->get($p->{'session_id'})
1557     or return { 'error' => "Can't resume session" }; #better error message
1558
1559   my $custnum = $session->{'custnum'};
1560
1561   my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1562     or return { 'error' => "unknown custnum $custnum" };
1563
1564   my $conf = new FS::Conf;
1565
1566   my @legacy_cust_bill = $cust_main->legacy_cust_bill;
1567
1568   my @cust_bill = grep ! $_->hide, $cust_main->cust_bill;
1569
1570   my $balance = 0;
1571   my $invoices = [
1572     map {
1573       #not super efficient, we also run cust_bill_pay/cust_credited inside owed
1574       my @payments_and_credits = sort {$b->_date <=> $a->_date} ($_->cust_bill_pay,$_->cust_credited);
1575       my $owed = $_->owed;
1576       $balance += $owed;
1577       +{ 'invnum'       => $_->invnum,
1578          '_date'        => $_->_date,
1579          'date'         => time2str("%b %o, %Y", $_->_date),
1580          'date_short'   => time2str("%m-%d-%Y",  $_->_date),
1581          'previous'     => sprintf('%.2f', ($_->previous)[0]),
1582          'charged'      => sprintf('%.2f', $_->charged),
1583          'owed'         => sprintf('%.2f', $owed),
1584          'balance'      => sprintf('%.2f', $balance),
1585          'lastpay'      => @payments_and_credits 
1586                            ? time2str("%b %o, %Y", $payments_and_credits[0]->_date)
1587                            : '',
1588       }
1589     } @cust_bill
1590   ];
1591
1592   return  { 'error'       => '',
1593             'balance'     => $cust_main->balance,
1594             'money_char'  => $conf->config("money_char") || '$',
1595             'invoices'    => $invoices,
1596             'legacy_invoices' => [
1597               map {
1598                     +{ 'legacyinvnum' => $_->legacyinvnum,
1599                        'legacyid'     => $_->legacyid,
1600                        '_date'        => $_->_date,
1601                        'date'         => time2str("%b %o, %Y", $_->_date),
1602                        'date_short'   => time2str("%m-%d-%Y",  $_->_date),
1603                        'charged'      => sprintf('%.2f', $_->charged),
1604                        'has_content'  => (    length($_->content_pdf)
1605                                            || length($_->content_html) ),
1606                      }
1607                   }
1608                   @legacy_cust_bill
1609             ],
1610           };
1611 }
1612
1613 sub cancel {
1614   my $p = shift;
1615   my $session = _cache->get($p->{'session_id'})
1616     or return { 'error' => "Can't resume session" }; #better error message
1617
1618   my $custnum = $session->{'custnum'};
1619
1620   my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1621     or return { 'error' => "unknown custnum $custnum" };
1622
1623   my @errors = $cust_main->cancel( 'quiet'=>1 );
1624
1625   my $error = scalar(@errors) ? join(' / ', @errors) : '';
1626
1627   return { 'error' => $error };
1628
1629 }
1630
1631 sub list_pkgs {
1632   my $p = shift;
1633
1634   my($context, $session, $custnum) = _custoragent_session_custnum($p);
1635   return { 'error' => $session } if $context eq 'error';
1636
1637   my $search = { 'custnum' => $custnum };
1638   $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
1639   my $cust_main = qsearchs('cust_main', $search )
1640     or return { 'error' => "unknown custnum $custnum" };
1641
1642   my $conf = new FS::Conf;
1643   my $immutable = $conf->exists('selfservice_immutable-package');
1644   
1645 # the duplication below is necessary:
1646 # 1. to maintain the current buggy behaviour wrt the cust_pkg and part_pkg
1647 # hashes overwriting each other (setup and no_auto fields). Fixing that is a
1648 # non-backwards-compatible change breaking the software of anyone using the API
1649 # instead of the stock selfservice
1650 # 2. to return cancelled packages as well - for wholesale and non-wholesale
1651   if( $conf->exists('selfservice_server-view-wholesale') ) {
1652     return { 'svcnum'   => $session->{'svcnum'},
1653             'custnum'  => $custnum,
1654             'cust_pkg' => [ map {
1655                           { $_->hash,
1656                             immutable => $immutable,
1657                             part_pkg => [ map $_->hashref, $_->part_pkg ],
1658                             part_svc =>
1659                               [ map $_->hashref, $_->available_part_svc ],
1660                             cust_svc => 
1661                               [ map { my $ref = { $_->hash,
1662                                                   label => [ $_->label ],
1663                                                 };
1664                                       $ref->{_password} = $_->svc_x->_password
1665                                         if $context eq 'agent'
1666                                         && $conf->exists('agent-showpasswords')
1667                                         && $_->part_svc->svcdb eq 'svc_acct';
1668                                       $ref;
1669                                     } $_->cust_svc
1670                               ],
1671                           };
1672                         } $cust_main->cust_pkg
1673                   ],
1674     'small_custview' =>
1675       small_custview( $cust_main, $conf->config('countrydefault') ),
1676     'wholesale_view' => 1,
1677     'login_svcpart' => [ $conf->config('selfservice_server-login_svcpart') ],
1678     'date_format' => $conf->config('date_format') || '%m/%d/%Y',
1679     'lnp' => $conf->exists('svc_phone-lnp'),
1680       };
1681   }
1682
1683   { 'svcnum'   => $session->{'svcnum'},
1684     'custnum'  => $custnum,
1685     'cust_pkg' => [ map {
1686                           my $primary_cust_svc = $_->primary_cust_svc;
1687                           +{ $_->hash,
1688                             $_->part_pkg->hash,
1689                             immutable   => $immutable,
1690                             pkg_label   => $_->pkg_locale,
1691                             status      => $_->status,
1692                             statuscolor => $_->statuscolor,
1693                             part_svc =>
1694                               [ map { $_->hashref }
1695                                   grep { $_->selfservice_access ne 'hidden' }
1696                                     $_->available_part_svc
1697                               ],
1698                             cust_svc => 
1699                               [ map { my $ref = { $_->hash,
1700                                                   label => [ $_->label ],
1701                                                 };
1702                                       $ref->{_password} = $_->svc_x->_password
1703                                         if $context eq 'agent'
1704                                         && $conf->exists('agent-showpasswords')
1705                                         && $_->part_svc->svcdb eq 'svc_acct';
1706                                       $ref->{svchash} = { $_->svc_x->hash } if 
1707                                         $_->part_svc->svcdb eq 'svc_phone';
1708                                       $ref->{svchash}->{svcpart} =  $_->part_svc->svcpart
1709                                         if $_->part_svc->svcdb eq 'svc_phone'; # hack
1710                                       $ref;
1711                                     }
1712                                   grep { $_->part_svc->selfservice_access ne 'hidden' }
1713                                     $_->cust_svc
1714                               ],
1715                             primary_cust_svc =>
1716                               $primary_cust_svc
1717                                 ? { $primary_cust_svc->hash,
1718                                     label => [ $primary_cust_svc->label ],
1719                                     finger => $primary_cust_svc->svc_x->finger, #uuh
1720                                     $primary_cust_svc->part_svc->hash,
1721                                   }
1722                                 : {}, #'' ?
1723                           };
1724                         } $cust_main->ncancelled_pkgs
1725                   ],
1726     'small_custview' =>
1727       small_custview( $cust_main, $conf->config('countrydefault') ),
1728     'date_format' => $conf->config('date_format') || '%m/%d/%Y',
1729   };
1730
1731 }
1732
1733 sub list_svcs {
1734   my $p = shift;
1735
1736   my($context, $session, $custnum) = _custoragent_session_custnum($p);
1737   return { 'error' => $session } if $context eq 'error';
1738
1739   my $conf = new FS::Conf;
1740
1741   my $hide_usage = $conf->exists('selfservice_hide-usage') ? 1 : 0;
1742   my $search = { 'custnum' => $custnum };
1743   $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
1744   my $cust_main = qsearchs('cust_main', $search )
1745     or return { 'error' => "unknown custnum $custnum" };
1746
1747   my $pkgnum = $session->{'pkgnum'} || $p->{'pkgnum'} || '';
1748   if ( ! $pkgnum && $p->{'svcnum'} ) {
1749     my $cust_svc = qsearchs('cust_svc', { 'svcnum' => $p->{'svcnum'} } );
1750     $pkgnum = $cust_svc->pkgnum if $cust_svc;
1751   }
1752
1753   my @cust_svc = ();
1754   my @cust_pkg_usage = ();
1755   foreach my $cust_pkg ( $p->{'ncancelled'} 
1756                          ? $cust_main->ncancelled_pkgs
1757                          : $cust_main->unsuspended_pkgs ) {
1758     next if $pkgnum && $cust_pkg->pkgnum != $pkgnum;
1759     push @cust_svc, @{[ $cust_pkg->cust_svc ]}; #@{[ ]} to force array context
1760     push @cust_pkg_usage, $cust_pkg->cust_pkg_usage;
1761   }
1762
1763   @cust_svc = grep { $_->part_svc->selfservice_access ne 'hidden' } @cust_svc;
1764   my %usage_pools;
1765   if (!$hide_usage) {
1766     foreach (@cust_pkg_usage) {
1767       my $part = $_->part_pkg_usage;
1768       my $tag = $part->description . ($part->shared ? 1 : 0);
1769       my $row = $usage_pools{$tag} 
1770             ||= [ $part->description, 0, 0, $part->shared ? 1 : 0 ];
1771       $row->[1] += sprintf('%.1f', $_->minutes); # minutes remaining
1772       $row->[2] += $part->minutes; # minutes total
1773     }
1774   } # otherwise just leave them empty
1775
1776   if ( $p->{'svcdb'} ) {
1777     my $svcdb = ref($p->{'svcdb'}) eq 'HASH'
1778                   ? $p->{'svcdb'}
1779                   : ref($p->{'svcdb'}) eq 'ARRAY'
1780                     ? { map { $_=>1 } @{ $p->{'svcdb'} } }
1781                     : { $p->{'svcdb'} => 1 };
1782     @cust_svc = grep $svcdb->{ $_->part_svc->svcdb }, @cust_svc
1783   }
1784
1785   #@svc_x = sort { $a->domain cmp $b->domain || $a->username cmp $b->username }
1786   #              @svc_x;
1787
1788   my @svcs; # stuff to return to the client
1789   foreach my $cust_svc (@cust_svc) {
1790     my $svc_x = $cust_svc->svc_x;
1791     my($label, $value) = $cust_svc->label;
1792     my $part_svc = $cust_svc->part_svc;
1793     my $svcdb = $part_svc->svcdb;
1794     my $cust_pkg = $cust_svc->cust_pkg;
1795     my $part_pkg = $cust_pkg->part_pkg;
1796
1797     my %hash = (
1798       'svcnum'         => $cust_svc->svcnum,
1799       'display_svcnum' => $cust_svc->display_svcnum,
1800       'svcdb'          => $svcdb,
1801       'label'          => $label,
1802       'value'          => $value,
1803       'pkg_label'      => $cust_pkg->pkg_locale,
1804       'pkg_status'     => $cust_pkg->status,
1805       'readonly'       => ($part_svc->selfservice_access eq 'readonly'),
1806     );
1807
1808     # would it make sense to put this in a svc_* method?
1809
1810     if ( $svcdb eq 'svc_acct' ) {
1811       foreach (qw(username email finger seconds)) {
1812         $hash{$_} = $svc_x->$_;
1813       }
1814
1815       if (!$hide_usage) {
1816         %hash = (
1817           %hash,
1818           'upbytes'    => display_bytecount($svc_x->upbytes),
1819           'downbytes'  => display_bytecount($svc_x->downbytes),
1820           'totalbytes' => display_bytecount($svc_x->totalbytes),
1821
1822           'recharge_amount'  => $part_pkg->option('recharge_amount',1),
1823           'recharge_seconds' => $part_pkg->option('recharge_seconds',1),
1824           'recharge_upbytes'    =>
1825             display_bytecount($part_pkg->option('recharge_upbytes',1)),
1826           'recharge_downbytes'  =>
1827             display_bytecount($part_pkg->option('recharge_downbytes',1)),
1828           'recharge_totalbytes' =>
1829             display_bytecount($part_pkg->option('recharge_totalbytes',1)),
1830           # more...
1831         );
1832       }
1833
1834     } elsif ( $svcdb eq 'svc_dsl' ) {
1835
1836       $hash{'phonenum'} = $svc_x->phonenum;
1837       if ( $svc_x->first || $svc_x->get('last') || $svc_x->company ) {
1838         $hash{'name'} = $svc_x->first. ' '. $svc_x->get('last');
1839         $hash{'name'} = $svc_x->company. ' ('. $hash{'name'}. ')'
1840           if $svc_x->company;
1841       } else {
1842         $hash{'name'} = $cust_main->name;
1843       }
1844       # no usage to hide here
1845
1846     } elsif ( $svcdb eq 'svc_phone' or $svcdb eq 'svc_pbx' ) {
1847       if (!$hide_usage) {
1848         # could potentially show lots of things...
1849         $hash{'outbound'} = 1;
1850         $hash{'inbound'}  = 0;
1851         if ( $svcdb eq 'svc_phone' ) {
1852           if ( $part_pkg->plan eq 'voip_inbound' ) {
1853             $hash{'outbound'} = 0;
1854             $hash{'inbound'}  = 1;
1855           } elsif ( $part_pkg->option('selfservice_inbound_format')
1856                 or  $conf->config('selfservice-default_inbound_cdr_format')
1857           ) {
1858             $hash{'inbound'}  = 1;
1859           }
1860         }
1861         foreach (qw(inbound outbound)) {
1862           # hmm...we can't filter by status here, because there might
1863           # not be cdr_terminations at all.  have to go by date.
1864           # find all since the last bill date.
1865           # XXX cdr types?  we are going to need them.
1866           if ( $hash{$_} ) {
1867             my $sum_cdr = $svc_x->sum_cdrs(
1868               'inbound' => ( $_ eq 'inbound' ? 1 : 0 ),
1869               'begin'   => ($cust_pkg->last_bill || 0),
1870               'nonzero' => 1,
1871               'disable_charged_party' => 1,
1872             );
1873             $hash{$_} = $sum_cdr->hashref;
1874           }
1875         }
1876       } # not hiding usage
1877     } # svcdb
1878
1879     push @svcs, \%hash;
1880   } # foreach $cust_svc
1881
1882   return { 
1883     'svcnum'   => $session->{'svcnum'},
1884     'custnum'  => $custnum,
1885     'date_format' => $conf->config('date_format') || '%m/%d/%Y',
1886     'view_usage_nodomain' => $conf->exists('selfservice-view_usage_nodomain'),
1887     'svcs'     => \@svcs,
1888     'usage_pools' => [
1889       map { $usage_pools{$_} }
1890       sort { $a cmp $b }
1891       keys %usage_pools
1892     ],
1893     'hide_usage' => $hide_usage,
1894   };
1895
1896 }
1897
1898 sub _customer_svc_x {
1899   my($custnum, $svcnum, $table) = (shift, shift, shift);
1900   my $hashref = ref($svcnum) ? $svcnum : { 'svcnum' => $svcnum };
1901
1902   $custnum =~ /^(\d+)$/ or die "illegal custnum";
1903   my $search = " AND custnum = $1";
1904   #$search .= " AND agentnum = ". $session->{'agentnum'} if $context eq 'agent';
1905
1906   qsearchs( {
1907     'table'     => ($table || 'svc_acct'),
1908     'addl_from' => 'LEFT JOIN cust_svc  USING ( svcnum  ) '.
1909                    'LEFT JOIN cust_pkg  USING ( pkgnum  ) ',#.
1910                    #'LEFT JOIN cust_main USING ( custnum ) ',
1911     'hashref'   => $hashref,
1912     'extra_sql' => $search, #important
1913   } );
1914
1915 }
1916
1917 sub svc_status_html {
1918   my $p = shift;
1919
1920   my($context, $session, $custnum) = _custoragent_session_custnum($p);
1921   return { 'error' => $session } if $context eq 'error';
1922
1923   #XXX only svc_dsl for now
1924   my $svc_x = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_dsl')
1925     or return { 'error' => "Service not found" };
1926
1927   my $html = $svc_x->getstatus_html;
1928
1929   return { 'html' => $html };
1930
1931 }
1932
1933 sub svc_status_hash {
1934   my $p = shift;
1935
1936   my($context, $session, $custnum) = _custoragent_session_custnum($p);
1937   return { 'error' => $session } if $context eq 'error';
1938
1939   #XXX only svc_acct for now
1940   my $svc_x = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_acct')
1941     or return { 'error' => "Service not found" };
1942
1943   my ( $html, $hashref ) = $svc_x->export_getstatus;
1944   return $hashref;
1945
1946 }
1947
1948 sub set_svc_status_hash    { _svc_method_X(shift, 'export_setstatus') }
1949 sub set_svc_status_listadd { _svc_method_X(shift, 'export_setstatus_listadd') }
1950 sub set_svc_status_listdel { _svc_method_X(shift, 'export_setstatus_listdel') }
1951 sub set_svc_status_vacationadd { _svc_method_X(shift, 'export_setstatus_vacationadd') }
1952 sub set_svc_status_vacationdel { _svc_method_X(shift, 'export_setstatus_vacationdel') }
1953
1954 sub _svc_method_X {
1955   my( $p, $method ) = @_;
1956
1957   my($context, $session, $custnum) = _custoragent_session_custnum($p);
1958   return { 'error' => $session } if $context eq 'error';
1959
1960   #XXX only svc_acct for now
1961   my $svc_x = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_acct')
1962     or return { 'error' => "Service not found" };
1963
1964   warn "$method ". join(' / ', map "$_=>".$p->{$_}, keys %$p )
1965     if $DEBUG;
1966   my $error = $svc_x->$method($p); #$p? returns error?
1967   return { 'error' => $error } if $error;
1968
1969   return {}; #? { 'error' => '' }
1970
1971 }
1972
1973 sub acct_forward_info {
1974   my $p = shift;
1975
1976   my($context, $session, $custnum) = _custoragent_session_custnum($p);
1977   return { 'error' => $session } if $context eq 'error';
1978
1979   my $svc_forward = _customer_svc_x( $custnum,
1980                                      { 'srcsvc' => $p->{'svcnum'} },
1981                                      'svc_forward',
1982                                    )
1983     or return { 'error' => '',
1984                 'dst'   => '',
1985               };
1986
1987   return { 'error' => '',
1988            'dst'   => $svc_forward->dst || $svc_forward->dstsvc_acct->email,
1989          };
1990
1991 }
1992
1993 sub process_acct_forward {
1994   my $p = shift;
1995   my($context, $session, $custnum) = _custoragent_session_custnum($p);
1996   return { 'error' => $session } if $context eq 'error';
1997
1998   my $old = _customer_svc_x( $custnum,
1999                              { 'srcsvc' => $p->{'svcnum'} },
2000                              'svc_forward',
2001                            );
2002
2003   if ( $p->{'dst'} eq '' ) {
2004     if ( $old ) {
2005       my $error = $old->delete;
2006       return { 'error' => $error };
2007     }
2008     return { 'error' => '' };
2009   }
2010
2011   my $new = new FS::svc_forward { 'srcsvc' => $p->{'svcnum'},
2012                                   'dst'    => $p->{'dst'},
2013                                 };
2014
2015   my $error;
2016   if ( $old ) {
2017     $new->svcnum($old->svcnum);
2018     my $cust_svc = $old->cust_svc;
2019     $new->svcpart($old->svcpart);
2020     $new->pkgnuym($old->pkgnum);
2021     $error = $new->replace($old);
2022   } else {
2023     my $conf = new FS::Conf;
2024     $new->svcpart($conf->config('selfservice-svc_forward_svcpart'));
2025
2026     my $svc_acct = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_acct' )
2027       or return { 'error' => 'No service' }; #how would we even get here?
2028
2029     $new->pkgnum( $svc_acct->cust_svc->pkgnum );
2030
2031     $error = $new->insert;
2032   }
2033
2034   return { 'error' => $error };
2035
2036 }
2037
2038 sub list_dsl_devices {
2039   my $p = shift;
2040
2041   my($context, $session, $custnum) = _custoragent_session_custnum($p);
2042   return { 'error' => $session } if $context eq 'error';
2043
2044   my $svc_dsl = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_dsl' )
2045     or return { 'error' => "Service not found" };
2046
2047   return {
2048     'devices' => [ map {
2049                          +{ 'mac_addr' => $_->mac_addr };
2050                        } $svc_dsl->dsl_device
2051                  ],
2052   };
2053
2054 }
2055
2056 sub add_dsl_device {
2057   my $p = shift;
2058
2059   my($context, $session, $custnum) = _custoragent_session_custnum($p);
2060   return { 'error' => $session } if $context eq 'error';
2061
2062   my $svc_dsl = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_dsl' )
2063     or return { 'error' => "Service not found" };
2064
2065   return { 'error' => 'No MAC address supplied' }
2066     unless length($p->{'mac_addr'});
2067
2068   my $dsl_device = new FS::dsl_device { 'svcnum'   => $svc_dsl->svcnum,
2069                                         'mac_addr' => scalar($p->{'mac_addr'}),
2070                                       };
2071   my $error = $dsl_device->insert;
2072   return { 'error' => $error };
2073
2074 }
2075
2076 sub delete_dsl_device {
2077   my $p = shift;
2078
2079   my($context, $session, $custnum) = _custoragent_session_custnum($p);
2080   return { 'error' => $session } if $context eq 'error';
2081
2082   my $svc_dsl = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_dsl' )
2083     or return { 'error' => "Service not found" };
2084
2085   my $dsl_device = qsearchs('dsl_device', { 'svcnum'   => $svc_dsl->svcnum,
2086                                             'mac_addr' => scalar($p->{'mac_addr'}),
2087                                           }
2088                            )
2089     or return { 'error' => 'Unknown MAC address: '. $p->{'mac_addr'} };
2090
2091   my $error = $dsl_device->delete;
2092   return { 'error' => $error };
2093
2094 }
2095
2096 sub port_graph {
2097   my $p = shift;
2098   _usage_details( \&_port_graph, $p,
2099                   'svcdb' => 'svc_port',
2100                 );
2101 }
2102
2103 sub _port_graph {
2104   my($svc_port, $begin, $end) = @_;
2105   my @usage = ();
2106   my $pngOrError = $svc_port->graph_png( start=>$begin, end=> $end );
2107   push @usage, { 'png' => $pngOrError };
2108   (@usage);
2109 }
2110
2111 sub _list_svc_usage {
2112   my($svc_acct, $begin, $end) = @_;
2113   my @usage = ();
2114   foreach my $part_export ( 
2115     map { qsearch ( 'part_export', { 'exporttype' => $_ } ) }
2116     qw( sqlradius sqlradius_withdomain )
2117   ) {
2118     push @usage, @ { $part_export->usage_sessions($begin, $end, $svc_acct) };
2119   }
2120   (@usage);
2121 }
2122
2123 sub list_svc_usage {
2124   _usage_details(\&_list_svc_usage, @_);
2125 }
2126
2127 sub _list_support_usage {
2128   my($svc_acct, $begin, $end) = @_;
2129   my @usage = ();
2130   foreach ( grep { $begin <= $_->_date && $_->_date <= $end }
2131             qsearch('acct_rt_transaction', { 'svcnum' => $svc_acct->svcnum })
2132           ) {
2133     push @usage, { 'seconds'  => $_->seconds,
2134                    'support'  => $_->support,
2135                    '_date'    => $_->_date,
2136                    'id'       => $_->transaction_id,
2137                    'creator'  => $_->creator,
2138                    'subject'  => $_->subject,
2139                    'status'   => $_->status,
2140                    'ticketid' => $_->ticketid,
2141                  };
2142   }
2143   (@usage);
2144 }
2145
2146 sub list_support_usage {
2147   _usage_details(\&_list_support_usage, @_);
2148 }
2149
2150 sub _list_cdr_usage {
2151   # XXX CDR type support...
2152   # XXX any way to do a paged search on this?
2153   # we have to return the results all at once...
2154   my($svc_x, $begin, $end, %opt) = @_;
2155   map [ $_->downstream_csv(%opt, 'keeparray' => 1) ],
2156     $svc_x->get_cdrs(
2157       'begin' => $begin,
2158       'end'   => $end,
2159       'disable_charged_party' => 1,
2160       %opt
2161     );
2162 }
2163
2164 sub list_cdr_usage {
2165   my $p = shift;
2166   _usage_details( \&_list_cdr_usage, $p );
2167 }
2168
2169 sub _usage_details {
2170   my($callback, $p, %opt) = @_;
2171   my $conf = FS::Conf->new;
2172
2173   if ( $conf->exists('selfservice_hide-usage') ) {
2174     return { 'error' => 'Viewing usage is not allowed.' };
2175   }
2176
2177   my($context, $session, $custnum) = _custoragent_session_custnum($p);
2178   return { 'error' => $session } if $context eq 'error';
2179
2180   my $search = { 'svcnum' => $p->{'svcnum'} };
2181   $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2182
2183   my $cust_svc = qsearchs( 'cust_svc', $search );
2184   return { 'error' => 'No service selected in list_svc_usage' } 
2185     unless $cust_svc;
2186
2187   my $svc_x = $cust_svc->svc_x;
2188   my $svcdb = $svc_x->table;
2189   my $cust_pkg = $cust_svc->cust_pkg;
2190   my $freq     = $cust_pkg->part_pkg->freq;
2191   my %callback_opt;
2192   my $header = [];
2193   if ( $svcdb eq 'svc_phone' or $svcdb eq 'svc_pbx' ) {
2194     my $format = '';
2195     if ( $p->{inbound} ) {
2196       $format = $cust_pkg->part_pkg->option('selfservice_inbound_format') 
2197                 || $conf->config('selfservice-default_inbound_cdr_format')
2198                 || 'source_default';
2199       $callback_opt{inbound} = 1;
2200     } else {
2201       $format = $cust_pkg->part_pkg->option('selfservice_format')
2202                 || $conf->config('selfservice-default_cdr_format')
2203                 || 'default';
2204     }
2205
2206     $callback_opt{format} = $format;
2207     $callback_opt{use_clid} = 1;
2208     $header = [ split(',', FS::cdr::invoice_header($format) ) ];
2209   }
2210
2211   my $start    = $cust_pkg->setup;
2212   #my $end      = $cust_pkg->bill; # or time?
2213   my $end      = time;
2214
2215   unless ( $p->{beginning} ) {
2216     $p->{beginning} = $cust_pkg->last_bill;
2217     $p->{ending}    = $end;
2218   }
2219
2220   die "illegal beginning" if $p->{beginning} !~ /^\d*$/;
2221   die "illegal ending"    if $p->{ending}    !~ /^\d*$/;
2222
2223   my (@usage) = &$callback($svc_x, $p->{beginning}, $p->{ending}, 
2224     %callback_opt
2225   );
2226
2227   if ( $conf->exists('selfservice-hide_cdr_price') ) {
2228     # ugly kludge, I know
2229     my ($delete_col) = grep { $header->[$_] eq 'Price' } (0..scalar(@$header));
2230     if (defined $delete_col) {
2231       delete($_->[$delete_col]) foreach ($header, @usage);
2232     }
2233   }
2234
2235   #kinda false laziness with FS::cust_main::bill, but perhaps
2236   #we should really change this bit to DateTime and DateTime::Duration
2237   #
2238   #change this bit to use Date::Manip? CAREFUL with timezones (see
2239   # mailing list archive)
2240   my ($nsec,$nmin,$nhour,$nmday,$nmon,$nyear) =
2241     (localtime($p->{ending}) )[0,1,2,3,4,5];
2242   my ($psec,$pmin,$phour,$pmday,$pmon,$pyear) =
2243     (localtime($p->{beginning}) )[0,1,2,3,4,5];
2244
2245   if ( $freq =~ /^\d+$/ ) {
2246     $nmon += $freq;
2247     until ( $nmon < 12 ) { $nmon -= 12; $nyear++; }
2248     $pmon -= $freq;
2249     until ( $pmon >= 0 ) { $pmon += 12; $pyear--; }
2250   } elsif ( $freq =~ /^(\d+)w$/ ) {
2251     my $weeks = $1;
2252     $nmday += $weeks * 7;
2253     $pmday -= $weeks * 7;
2254   } elsif ( $freq =~ /^(\d+)d$/ ) {
2255     my $days = $1;
2256     $nmday += $days;
2257     $pmday -= $days;
2258   } elsif ( $freq =~ /^(\d+)h$/ ) {
2259     my $hours = $1;
2260     $nhour += $hours;
2261     $phour -= $hours;
2262   } else {
2263     return { 'error' => "unparsable frequency: ". $freq };
2264   }
2265   
2266   my $previous  = timelocal_nocheck($psec,$pmin,$phour,$pmday,$pmon,$pyear);
2267   my $next      = timelocal_nocheck($nsec,$nmin,$nhour,$nmday,$nmon,$nyear);
2268
2269   { 
2270     'error'     => '',
2271     'svcnum'    => $p->{svcnum},
2272     'beginning' => $p->{beginning},
2273     'ending'    => $p->{ending},
2274     'inbound'   => $p->{inbound},
2275     'previous'  => ($previous > $start) ? $previous : $start,
2276     'next'      => ($next < $end) ? $next : $end,
2277     'header'    => $header,
2278     'usage'     => \@usage,
2279   };
2280 }
2281
2282 sub order_pkg {
2283   my $p = shift;
2284
2285   my($context, $session, $custnum) = _custoragent_session_custnum($p);
2286   return { 'error' => $session } if $context eq 'error';
2287
2288   my $search = { 'custnum' => $custnum };
2289   $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2290   my $cust_main = qsearchs('cust_main', $search )
2291     or return { 'error' => "unknown custnum $custnum" };
2292
2293   my $status = $cust_main->status;
2294
2295   my %order_pkg_options = ();
2296   if ( $p->{locationnum} > 0 ) {
2297     $order_pkg_options{locationnum} = delete($p->{locationnum});
2298   } elsif ( $p->{address1} ) {
2299     $order_pkg_options{'cust_location'} = new FS::cust_location {
2300       map { $_ => $p->{$_} }
2301         qw( address1 address2 city county state zip country )
2302     };
2303   }
2304
2305   #false laziness w/ClientAPI/Signup.pm
2306
2307   my $cust_pkg = new FS::cust_pkg ( {
2308     'custnum'  => $custnum,
2309     'pkgpart'  => $p->{'pkgpart'},
2310     'quantity' => $p->{'quantity'} || 1,
2311   } );
2312   my $error = $cust_pkg->check;
2313   return { 'error' => $error } if $error;
2314
2315   my @svc = ();
2316   unless ( $p->{'svcpart'} eq 'none' ) {
2317
2318     my $svcdb;
2319     my $svcpart = '';
2320     if ( $p->{'svcpart'} =~ /^(\d+)$/ ) {
2321       $svcpart = $1;
2322       my $part_svc = qsearchs('part_svc', { 'svcpart' => $svcpart } );
2323       return { 'error' => "Unknown svcpart $svcpart" } unless $part_svc;
2324       $svcdb = $part_svc->svcdb;
2325     } else {
2326       $svcdb = 'svc_acct';
2327     }
2328     $svcpart ||= $cust_pkg->part_pkg->svcpart($svcdb);
2329
2330     my %fields = (
2331       'svc_acct'     => [ qw( username domsvc _password sec_phrase popnum ) ],
2332       'svc_domain'   => [ qw( domain ) ],
2333       'svc_phone'    => [ qw( phonenum pin sip_password phone_name ) ],
2334       'svc_external' => [ qw( id title ) ],
2335       'svc_pbx'      => [ qw( id title ) ],
2336     );
2337   
2338     my $svc_x = "FS::$svcdb"->new( {
2339       'svcpart'   => $svcpart,
2340       map { $_ => $p->{$_} } @{$fields{$svcdb}}
2341     } );
2342     
2343     if ( $svcdb eq 'svc_acct' && exists($p->{"snarf_machine1"}) ) {
2344       my @acct_snarf;
2345       my $snarfnum = 1;
2346       while ( length($p->{"snarf_machine$snarfnum"}) ) {
2347         my $acct_snarf = new FS::acct_snarf ( {
2348           'machine'   => $p->{"snarf_machine$snarfnum"},
2349           'protocol'  => $p->{"snarf_protocol$snarfnum"},
2350           'username'  => $p->{"snarf_username$snarfnum"},
2351           '_password' => $p->{"snarf_password$snarfnum"},
2352         } );
2353         $snarfnum++;
2354         push @acct_snarf, $acct_snarf;
2355       }
2356       $svc_x->child_objects( \@acct_snarf );
2357     }
2358     
2359     my $y = $svc_x->setdefault; # arguably should be in new method
2360     return { 'error' => $y } if $y && !ref($y);
2361   
2362     $error = $svc_x->check;
2363     return { 'error' => $error } if $error;
2364
2365     push @svc, $svc_x;
2366
2367   }
2368
2369   $error = $cust_main->order_pkg(
2370     'cust_pkg' => $cust_pkg,
2371     'svcs'     => \@svc,
2372     'noexport' => 1,
2373     %order_pkg_options,
2374   );
2375   return { 'error' => $error } if $error;
2376
2377   my $conf = new FS::Conf;
2378   if ( $conf->exists('signup_server-realtime') ) {
2379
2380     my $bill_error = _do_bop_realtime( $cust_main, $status );
2381
2382     if ($bill_error) {
2383       $cust_pkg->cancel('quiet'=>1);
2384       return $bill_error;
2385     } else {
2386       $cust_pkg->reexport;
2387     }
2388
2389   } else {
2390     $cust_pkg->reexport;
2391   }
2392
2393   my $svcnum = $svc[0] ? $svc[0]->svcnum : '';
2394
2395   return { error=>'', pkgnum=>$cust_pkg->pkgnum, svcnum=>$svcnum };
2396
2397 }
2398
2399 sub change_pkg {
2400   my $p = shift;
2401
2402   my($context, $session, $custnum) = _custoragent_session_custnum($p);
2403   return { 'error' => $session } if $context eq 'error';
2404
2405   my $conf = new FS::Conf;
2406   my $immutable = $conf->exists('selfservice_immutable-package');
2407   return { 'error' => "Package modification disabled" } if $immutable;
2408
2409   my $search = { 'custnum' => $custnum };
2410   $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2411   my $cust_main = qsearchs('cust_main', $search )
2412     or return { 'error' => "unknown custnum $custnum" };
2413
2414   my $status = $cust_main->status;
2415   my $cust_pkg = qsearchs('cust_pkg', { 'pkgnum' => $p->{pkgnum} } )
2416     or return { 'error' => "unknown package $p->{pkgnum}" };
2417
2418   #if someone does need self-service package change of suspended packages,
2419   # figure out how to be more discriminating
2420   return { error=>"Can't change a suspended package", pkgnum=>$cust_pkg->pkgnum}
2421     if $cust_pkg->status eq 'suspended';
2422
2423   my $err_or_cust_pkg = $cust_pkg->change( 'pkgpart'  => $p->{'pkgpart'},
2424                                            'quantity' => $p->{'quantity'} || 1,
2425                                          );
2426
2427   return { error=>$err_or_cust_pkg, pkgnum=>$cust_pkg->pkgnum }
2428     unless ref($err_or_cust_pkg);
2429
2430   if ( $conf->exists('signup_server-realtime') ) {
2431
2432     my $bill_error = _do_bop_realtime( $cust_main, $status, 'no_invoice_void'=>1 );
2433
2434     if ($bill_error) {
2435       $err_or_cust_pkg->suspend;
2436       return $bill_error;
2437     } else {
2438       $err_or_cust_pkg->reexport;
2439     }
2440
2441   } else {  
2442     $err_or_cust_pkg->reexport;
2443   }
2444
2445   return { error => '', pkgnum => $cust_pkg->pkgnum };
2446
2447 }
2448
2449 sub order_recharge {
2450   my $p = shift;
2451
2452   my($context, $session, $custnum) = _custoragent_session_custnum($p);
2453   return { 'error' => $session } if $context eq 'error';
2454
2455   my $search = { 'custnum' => $custnum };
2456   $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2457   my $cust_main = qsearchs('cust_main', $search )
2458     or return { 'error' => "unknown custnum $custnum" };
2459
2460   my $status = $cust_main->status;
2461   my $cust_svc = qsearchs( 'cust_svc', { 'svcnum' => $p->{'svcnum'} } )
2462     or return { 'error' => "unknown service " . $p->{'svcnum'} };
2463
2464   my $svc_x = $cust_svc->svc_x;
2465   my $part_pkg = $cust_svc->cust_pkg->part_pkg;
2466
2467   my %vhash =
2468     map { $_ =~ /^recharge_(.*)$/; $1, $part_pkg->option($_, 1) } 
2469     qw ( recharge_seconds recharge_upbytes recharge_downbytes
2470          recharge_totalbytes );
2471   my $amount = $part_pkg->option('recharge_amount', 1); 
2472   
2473   my ($l, $v, $d) = $cust_svc->label;  # blah
2474   my $pkg = "Recharge $v"; 
2475
2476   my $bill_error = $cust_main->charge($amount, $pkg,
2477      "time: $vhash{seconds}, up: $vhash{upbytes}," . 
2478      "down: $vhash{downbytes}, total: $vhash{totalbytes}",
2479      $part_pkg->taxclass); #meh
2480
2481   my $conf = new FS::Conf;
2482   if ( $conf->exists('signup_server-realtime') && !$bill_error ) {
2483
2484     $bill_error = _do_bop_realtime( $cust_main, $status );
2485
2486     if ($bill_error) {
2487       return $bill_error;
2488     } else {
2489       my $error = $svc_x->recharge (\%vhash);
2490       return { 'error' => $error } if $error;
2491     }
2492
2493   } else {  
2494     my $error = $bill_error;
2495     $error ||= $svc_x->recharge (\%vhash);
2496     return { 'error' => $error } if $error;
2497   }
2498
2499   return { error => '', svc => $cust_svc->part_svc->svc };
2500
2501 }
2502
2503 sub _do_bop_realtime {
2504   my ($cust_main, $status, %opt) = @_;
2505
2506     my $old_balance = $cust_main->balance;
2507
2508     my @cust_bill;
2509     my $bill_error = $cust_main->bill(
2510       'return_bill'   => \@cust_bill,
2511     );
2512
2513     $bill_error ||= $cust_main->apply_payments_and_credits;
2514
2515     $bill_error ||= $cust_main->realtime_collect('selfservice' => 1)
2516       if $cust_main->payby =~ /^(CARD|CHEK)$/;
2517
2518     if (    $cust_main->balance > $old_balance
2519          && $cust_main->balance > 0
2520          && ( $cust_main->payby !~ /^(BILL|DCRD|DCHK)$/
2521                 || $status eq 'suspended'
2522             )
2523        )
2524     {
2525       unless ( $opt{'no_invoice_void'} ) {
2526
2527         #this used to apply a credit, but now we can void invoices...
2528         foreach my $cust_bill (@cust_bill) {
2529           my $voiderror = $cust_bill->void('automatic payment failed');
2530           warn "Error voiding cust bill after decline: $voiderror" if $voiderror;
2531         }
2532
2533       }
2534
2535       return { 'error' => '_decline', 'bill_error' => $bill_error };
2536     }
2537
2538     '';
2539 }
2540
2541 sub renew_info {
2542   my $p = shift;
2543
2544   my($context, $session, $custnum) = _custoragent_session_custnum($p);
2545   return { 'error' => $session } if $context eq 'error';
2546
2547   my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
2548     or return { 'error' => "unknown custnum $custnum" };
2549
2550   my @cust_pkg = sort { $a->bill <=> $b->bill }
2551                  grep { $_->part_pkg->freq ne '0' }
2552                  $cust_main->ncancelled_pkgs;
2553
2554   #return { 'error' => 'No active packages to renew.' } unless @cust_pkg;
2555
2556   my $total = $cust_main->balance;
2557
2558   my @array = map {
2559                     my $bill = $_->bill;
2560                     $total += $_->part_pkg->base_recur($_, \$bill);
2561                     my $renew_date = $_->part_pkg->add_freq($_->bill);
2562                     {
2563                       'pkgnum'             => $_->pkgnum,
2564                       'amount'             => sprintf('%.2f', $total),
2565                       'bill_date'          => $_->bill,
2566                       'bill_date_pretty'   => time2str('%x', $_->bill),
2567                       'renew_date'         => $renew_date,
2568                       'renew_date_pretty'  => time2str('%x', $renew_date),
2569                       'expire_date'        => $_->expire,
2570                       'expire_date_pretty' => time2str('%x', $_->expire),
2571                     };
2572                   }
2573                   @cust_pkg;
2574
2575   return { 'dates' => \@array };
2576
2577 }
2578
2579 sub payment_info_renew_info {
2580   my $p = shift;
2581   my $renew_info   = renew_info($p);
2582   my $payment_info = payment_info($p);
2583   return { %$renew_info,
2584            %$payment_info,
2585          };
2586 }
2587
2588 sub order_renew {
2589   my $p = shift;
2590
2591   my($context, $session, $custnum) = _custoragent_session_custnum($p);
2592   return { 'error' => $session } if $context eq 'error';
2593
2594   my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
2595     or return { 'error' => "unknown custnum $custnum" };
2596
2597   my $date = $p->{'date'};
2598
2599   my $now = time;
2600
2601   #freeside-daily -n -d $date fs_daily $custnum
2602   $cust_main->bill_and_collect( 'time'         => $date,
2603                                 'invoice_time' => $now,
2604                                 'actual_time'  => $now,
2605                                 'check_freq'   => '1d',
2606                               );
2607
2608   return { 'error' => '' };
2609
2610 }
2611
2612 sub suspend_pkg {
2613   my $p = shift;
2614   my $session = _cache->get($p->{'session_id'})
2615     or return { 'error' => "Can't resume session" }; #better error message
2616
2617   my $custnum = $session->{'custnum'};
2618
2619   my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
2620     or return { 'error' => "unknown custnum $custnum" };
2621
2622   my $conf = new FS::Conf;
2623   my $reasonnum = 
2624     $conf->config('selfservice-self_suspend_reason', $cust_main->agentnum)
2625       or return { 'error' => 'Permission denied' };
2626
2627   my $pkgnum = $p->{'pkgnum'};
2628
2629   my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
2630                                         'pkgnum'  => $pkgnum,   } )
2631     or return { 'error' => "unknown pkgnum $pkgnum" };
2632
2633   my $error = $cust_pkg->suspend(reason => $reasonnum);
2634   return { 'error' => $error };
2635
2636 }
2637
2638 sub cancel_pkg {
2639   my $p = shift;
2640   my $session = _cache->get($p->{'session_id'})
2641     or return { 'error' => "Can't resume session" }; #better error message
2642
2643   my $custnum = $session->{'custnum'};
2644
2645   my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
2646     or return { 'error' => "unknown custnum $custnum" };
2647
2648   my $pkgnum = $p->{'pkgnum'};
2649
2650   my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
2651                                         'pkgnum'  => $pkgnum,   } )
2652     or return { 'error' => "unknown pkgnum $pkgnum" };
2653
2654   my $error = $cust_pkg->cancel('quiet' => 1);
2655   return { 'error' => $error };
2656
2657 }
2658
2659 sub provision_phone {
2660   my $p = shift;
2661   my @bulkdid;
2662   @bulkdid = @{$p->{'bulkdid'}} if $p->{'bulkdid'};
2663
2664   #editing an existing phone number
2665   if ( $p->{'svcnum'} && $p->{'svcnum'} =~ /^\d+$/ ) {
2666       my($context, $session, $custnum) = _custoragent_session_custnum($p);
2667       return { 'error' => $session } if $context eq 'error';
2668     
2669       my $svc_phone = qsearchs('svc_phone', { svcnum => $p->{'svcnum'} });
2670       return { 'error' => 'service not found' } unless $svc_phone;
2671       return { 'error' => 'invalid svcnum' } 
2672         if $svc_phone && $svc_phone->cust_svc->cust_pkg->custnum != $custnum;
2673
2674       $svc_phone->email($p->{'email'}) 
2675         if $svc_phone->email ne $p->{'email'} && $p->{'email'} =~ /^([\w\.\d@]+|)$/;
2676       $svc_phone->forwarddst($p->{'forwarddst'}) 
2677         if $svc_phone->forwarddst ne $p->{'forwarddst'} 
2678             && $p->{'forwarddst'} =~ /^(\d+|)$/;
2679       return { 'error' => $svc_phone->replace };
2680  }
2681
2682   # single DID LNP
2683   unless ( $p->{'lnp'} ) {
2684     $p->{'lnp_desired_due_date'} = parse_datetime($p->{'lnp_desired_due_date'});
2685     $p->{'lnp_status'} = "portingin";
2686     return _provision( 'FS::svc_phone',
2687                   [qw(lnp_desired_due_date lnp_other_provider 
2688                     lnp_other_provider_account phonenum countrycode lnp_status)],
2689                   [qw(phonenum countrycode)],
2690                   $p,
2691                   @_
2692                 );
2693   }
2694
2695   # single DID order (the usual case)
2696   unless (scalar(@bulkdid)) {
2697     return _provision( 'FS::svc_phone',
2698                   [qw(phonenum countrycode)],
2699                   [qw(phonenum countrycode)],
2700                   $p,
2701                   @_
2702                 );
2703   }
2704
2705   # bulk DID order case
2706   my $error;
2707   foreach my $did ( @bulkdid ) {
2708     $did =~ s/[^0-9]//g;
2709     $error = _provision( 'FS::svc_phone',
2710               [qw(phonenum countrycode)],
2711               [qw(phonenum countrycode)],
2712               {
2713                 'pkgnum' => $p->{'pkgnum'},
2714                 'svcpart' => $p->{'svcpart'},
2715                 'phonenum' => $did,
2716                 'countrycode' => $p->{'countrycode'},
2717                 'session_id' => $p->{'session_id'},
2718               }
2719             );
2720     return $error if ($error->{'error'} && length($error->{'error'}) > 1);
2721   }
2722   { 'bulkdid' => [ @bulkdid ], 'svc' => $error->{'svc'} }
2723 }
2724
2725 sub provision_pbx {
2726   my $p = shift;
2727   warn "provision_pbx called\n"
2728     if $DEBUG;
2729
2730   warn "provision_pbx calling _provision\n"
2731     if $DEBUG;
2732   _provision( 'FS::svc_pbx',
2733               [qw(id title max_extensions max_simultaneous ip_addr)],
2734               [qw(id title max_extensions max_simultaneous ip_addr)],
2735               $p,
2736               @_
2737             );
2738 }
2739
2740 sub provision_acct {
2741   my $p = shift;
2742   warn "provision_acct called\n"
2743     if $DEBUG;
2744
2745   return { 'error' => gettext('passwords_dont_match') }
2746     if $p->{'_password'} ne $p->{'_password2'};
2747   return { 'error' => gettext('empty_password') }
2748     unless length($p->{'_password'});
2749  
2750   if ($p->{'domsvc'}) {
2751     my %domains = domain_select_hash FS::svc_acct(map { $_ => $p->{$_} }
2752                                                   qw ( svcpart pkgnum ) );
2753     return { 'error' => gettext('invalid_domain') }
2754       unless ($domains{$p->{'domsvc'}});
2755   }
2756
2757   warn "provision_acct calling _provision\n"
2758     if $DEBUG;
2759   _provision( 'FS::svc_acct',
2760               [qw(username _password domsvc)],
2761               [qw(username _password domsvc)],
2762               $p,
2763               @_
2764             );
2765 }
2766
2767 sub provision_external {
2768   my $p = shift;
2769   #_provision( 'FS::svc_external', [qw(id title)], [qw(id title)], $p, @_ );
2770   _provision( 'FS::svc_external',
2771               [],
2772               [qw(id title)],
2773               $p,
2774               @_
2775             );
2776 }
2777
2778 sub provision_forward {
2779   my $p = shift;
2780   _provision( 'FS::svc_forward',
2781               ['srcsvc','src','dstsvc','dst'],
2782               [],
2783               $p,
2784             );
2785 }
2786
2787 sub _provision {
2788   my( $class, $fields, $return_fields, $p ) = splice(@_, 0, 4);
2789   warn "_provision called for $class\n"
2790     if $DEBUG;
2791
2792   my($context, $session, $custnum) = _custoragent_session_custnum($p);
2793   return { 'error' => $session } if $context eq 'error';
2794
2795   my $search = { 'custnum' => $custnum };
2796   $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2797   my $cust_main = qsearchs('cust_main', $search )
2798     or return { 'error' => "unknown custnum $custnum" };
2799
2800   my $pkgnum = $p->{'pkgnum'};
2801
2802   warn "searching for custnum $custnum pkgnum $pkgnum\n"
2803     if $DEBUG;
2804   my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
2805                                         'pkgnum'  => $pkgnum,
2806                                                                } )
2807     or return { 'error' => "unknown pkgnum $pkgnum" };
2808
2809   warn "searching for svcpart ". $p->{'svcpart'}. "\n"
2810     if $DEBUG;
2811   my $part_svc = qsearchs('part_svc', { 'svcpart' => $p->{'svcpart'} } )
2812     or return { 'error' => "unknown svcpart $p->{'svcpart'}" };
2813
2814   return { error=> 'svcpart '. $p->{'svcpart'}. " is not a $class definition" }
2815     if $class ne 'FS::'. $part_svc->svcdb;
2816
2817   warn "creating $class record\n"
2818     if $DEBUG;
2819   my $svc_x = $class->new( {
2820     'pkgnum'  => $p->{'pkgnum'},
2821     'svcpart' => $p->{'svcpart'},
2822     map { $_ => $p->{$_} } @$fields
2823   } );
2824
2825   my %insert_args = ();
2826   #i shouldn't be a special case here (pass an option or something)
2827   if ( $class eq 'FS::svc_phone'
2828          && grep length($p->{$_}), @location_editable_fields
2829      )
2830   {
2831     $insert_args{'cust_location'} = new FS::cust_location {
2832       map { $_ => $p->{$_} } @location_editable_fields
2833     };
2834   }
2835
2836   warn "inserting $class record\n"
2837     if $DEBUG;
2838   my $error = $svc_x->insert(%insert_args);
2839
2840   unless ( $error ) {
2841     warn "finding inserted record for svcnum ". $svc_x->svcnum. "\n"
2842       if $DEBUG;
2843     $svc_x = qsearchs($svc_x->table, { 'svcnum' => $svc_x->svcnum })
2844   }
2845
2846   my $return = { 'svc'   => $part_svc->svc,
2847                  'error' => $error,
2848                  map { $_ => $svc_x->get($_) } @$return_fields
2849                };
2850   warn "_provision returning ". Dumper($return). "\n"
2851     if $DEBUG;
2852   return $return;
2853
2854 }
2855
2856 sub part_svc_info {
2857   my $p = shift;
2858
2859   my($context, $session, $custnum) = _custoragent_session_custnum($p);
2860   return { 'error' => $session } if $context eq 'error';
2861
2862   my $search = { 'custnum' => $custnum };
2863   $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2864   my $cust_main = qsearchs('cust_main', $search )
2865     or return { 'error' => "unknown custnum $custnum" };
2866
2867   my $pkgnum = $p->{'pkgnum'};
2868
2869   my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
2870                                         'pkgnum'  => $pkgnum,
2871                                                                } )
2872     or return { 'error' => "unknown pkgnum $pkgnum" };
2873
2874   my $svcpart = $p->{'svcpart'};
2875
2876   my $pkg_svc = qsearchs('pkg_svc', { 'pkgpart' => $cust_pkg->pkgpart,
2877                                       'svcpart' => $svcpart,           } )
2878     or return { 'error' => "unknown svcpart $svcpart for pkgnum $pkgnum" };
2879   my $part_svc = $pkg_svc->part_svc;
2880
2881   my $conf = new FS::Conf;
2882
2883   my $ret = {
2884     'svc'     => $part_svc->svc,
2885     'svcdb'   => $part_svc->svcdb,
2886     'pkgnum'  => $pkgnum,
2887     'svcpart' => $svcpart,
2888     'custnum' => $custnum,
2889
2890     'security_phrase' => 0, #XXX !
2891     'svc_acct_pop'    => [], #XXX !
2892     'popnum'          => '',
2893     'init_popstate'   => '',
2894     'popac'           => '',
2895     'acstate'         => '',
2896
2897     'small_custview' =>
2898       small_custview( $cust_main, $conf->config('countrydefault') ),
2899
2900   };
2901
2902   if ($p->{'svcnum'} && $p->{'svcnum'} =~ /^\d+$/ 
2903                      && $ret->{'svcdb'} eq 'svc_phone') {
2904         $ret->{'svcnum'} = $p->{'svcnum'};
2905         my $svc_phone = qsearchs('svc_phone', { svcnum => $p->{'svcnum'} });
2906         if ( $svc_phone && $svc_phone->cust_svc->cust_pkg->custnum == $custnum ) {
2907             $ret->{'email'} = $svc_phone->email;
2908             $ret->{'forwarddst'} = $svc_phone->forwarddst;
2909         }
2910   }
2911
2912   if ($ret->{'svcdb'} eq 'svc_forward') {
2913     $ret->{'forward_emails'} = {$cust_pkg->forward_emails()};
2914   }
2915
2916   $ret;
2917 }
2918
2919 sub unprovision_svc {
2920   my $p = shift;
2921
2922   my($context, $session, $custnum) = _custoragent_session_custnum($p);
2923   return { 'error' => $session } if $context eq 'error';
2924
2925   my $search = { 'custnum' => $custnum };
2926   $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2927   my $cust_main = qsearchs('cust_main', $search )
2928     or return { 'error' => "unknown custnum $custnum" };
2929
2930   my $svcnum = $p->{'svcnum'};
2931
2932   my $cust_svc = qsearchs('cust_svc', { 'svcnum'  => $svcnum, } )
2933     or return { 'error' => "unknown svcnum $svcnum" };
2934
2935   return { 'error' => "Service $svcnum does not belong to customer $custnum" }
2936     unless $cust_svc->cust_pkg->custnum == $custnum;
2937
2938   my $conf = new FS::Conf;
2939
2940   return { 'svc'   => $cust_svc->part_svc->svc,
2941            'error' => $cust_svc->cancel,
2942            'small_custview' =>
2943              small_custview( $cust_main, $conf->config('countrydefault') ),
2944          };
2945
2946 }
2947
2948 sub myaccount_passwd {
2949   my $p = shift;
2950   my($context, $session, $custnum) = _custoragent_session_custnum($p);
2951   return { 'error' => $session } if $context eq 'error';
2952
2953   return { 'error' => "New passwords don't match." }
2954     if $p->{'new_password'} ne $p->{'new_password2'};
2955
2956   return { 'error' => 'Enter new password' }
2957     unless length($p->{'new_password'});
2958
2959   #my $search = { 'custnum' => $custnum };
2960   #$search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2961   $custnum =~ /^(\d+)$/ or die "illegal custnum";
2962   my $search = " AND custnum = $1";
2963   $search .= " AND agentnum = ". $session->{'agentnum'} if $context eq 'agent';
2964
2965   my $svc_acct = qsearchs( {
2966     'table'     => 'svc_acct',
2967     'addl_from' => 'LEFT JOIN cust_svc  USING ( svcnum  ) '.
2968                    'LEFT JOIN cust_pkg  USING ( pkgnum  ) '.
2969                    'LEFT JOIN cust_main USING ( custnum ) ',
2970     'hashref'   => { 'svcnum' => $p->{'svcnum'}, },
2971     'extra_sql' => $search, #important
2972   } )
2973     or return { 'error' => "Service not found" };
2974
2975   my $error = '';
2976
2977   my $conf = new FS::Conf;
2978
2979   return { 'error' => 'Incorrect current password.' }
2980     if  ( exists($p->{'old_password'})
2981           || $conf->exists('selfservice-password_change_oldpass')
2982         )
2983     && ! $svc_acct->check_password($p->{'old_password'});
2984
2985     # should move password length checks into is_password_allowed
2986   $error = 'Password too short.'
2987     if length($p->{'new_password'}) < ($conf->config('passwordmin') || 6);
2988   $error = 'Password too long.'
2989     if length($p->{'new_password'}) > ($conf->config('passwordmax') || 8);
2990
2991   $error ||= $svc_acct->is_password_allowed($p->{'new_password'})
2992          ||  $svc_acct->set_password($p->{'new_password'})
2993          ||  $svc_acct->replace();
2994
2995   #regular pw change in self-service should change contact pw too, otherwise its
2996   #way too confusing.  hell its confusing they're separate at all, but alas.
2997   #need to support the "ISP provides email that's used as a contact email" case
2998   #as well as we can.
2999   my $contact = FS::contact->by_selfservice_email($svc_acct->email);
3000   if ( $contact && qsearchs('cust_contact', { contactnum=> $contact->contactnum,
3001                                               custnum   => $custnum,
3002                                               selfservice_access => 'Y',
3003                                             }
3004                            )
3005   ) {
3006     #svc_acct was successful but this one returns an error?  "shouldn't happen"
3007     $error ||= $contact->change_password($p->{'new_password'});
3008   }
3009
3010   my($label, $value) = $svc_acct->cust_svc->label;
3011
3012   return { 'error' => $error,
3013            'label' => $label,
3014            'value' => $value,
3015          };
3016
3017 }
3018
3019 sub reset_passwd {
3020   my $p = shift;
3021
3022   my $info = skin_info($p);
3023
3024   my $conf = new FS::Conf;
3025   my $verification = $conf->config('selfservice-password_reset_verification')
3026     or return { %$info, 'error' => 'Password resets disabled' };
3027
3028   my $contact = '';
3029   my $svc_acct = '';
3030   my $cust_main = '';
3031   if ( $p->{'email'} ) { #new-style, changes contact and svc_acct
3032   
3033     $contact = FS::contact->by_selfservice_email($p->{'email'});
3034
3035     if ( $contact ) {
3036       my @cust_contact = grep $_->selfservice_access, $contact->cust_contact;
3037       $cust_main = $cust_contact[0]->cust_main if scalar(@cust_contact) == 1;
3038     }
3039
3040     #also look for an svc_acct, otherwise it would be super confusing
3041
3042     my($username, $domain) = split('@', $p->{'email'});
3043     my $svc_domain = qsearchs('svc_domain', { 'domain' => $domain } );
3044     if ( $svc_domain ) {
3045       $svc_acct = qsearchs('svc_acct', { 'username' => $username,
3046                                          'domsvc'   => $svc_domain->svcnum  }
3047                           );
3048       if ( $svc_acct ) {
3049         my $cust_pkg = $svc_acct->cust_svc->cust_pkg;
3050         $cust_main ||= $cust_pkg->cust_main if $cust_pkg;
3051
3052         #precaution: don't change svc_acct password not part of the same
3053         # customer as contact
3054         $svc_acct = '' if ! $cust_pkg
3055                        || $cust_pkg->custnum != $cust_main->custnum;
3056       }
3057       
3058     }
3059
3060     return { %$info, 'error' => 'Email address not found' }
3061       unless $contact || $svc_acct;
3062
3063   } elsif ( $p->{'username'} ) { #old style, looks in svc_acct only
3064
3065     my $svc_domain = qsearchs('svc_domain', { 'domain' => $p->{'domain'} } )
3066       or return { %$info, 'error' => 'Account not found' };
3067
3068     $svc_acct = qsearchs('svc_acct', { 'username' => $p->{'username'},
3069                                        'domsvc'   => $svc_domain->svcnum  }
3070                         )
3071       or return { %$info, 'error' => 'Account not found' };
3072
3073     my $cust_pkg = $svc_acct->cust_svc->cust_pkg
3074       or return { %$info, 'error' => 'Account not found' };
3075
3076     $cust_main = $cust_pkg->cust_main;
3077
3078   }
3079
3080   return { %$info, 'error' => 'Multi-customer contacts incompatible with customer-based verification' }
3081     if ! $cust_main && $verification ne 'email';
3082
3083   my %verify = (
3084     'email'   => sub { 1; },
3085     'paymask' => sub { 
3086       my( $p, $cust_main ) = @_;
3087       $cust_main->payby =~ /^(CARD|DCRD|CHEK|DCHK)$/
3088         && $p->{'paymask'} eq substr($cust_main->paymask, -4)
3089     },
3090     'amount'  => sub {
3091       my( $p, $cust_main ) = @_;
3092       my $cust_pay = qsearchs({
3093         'table' => 'cust_pay',
3094         'hashref' => { 'custnum' => $cust_main->custnum },
3095         'order_by' => 'ORDER BY _date DESC LIMIT 1',
3096       })
3097         or return 0;
3098
3099       $p->{'amount'} == $cust_pay->paid;
3100     },
3101     'zip'     => sub {
3102       my( $p, $cust_main ) = @_;
3103       $p->{'zip'} eq $cust_main->zip
3104         || ( $cust_main->ship_zip && $p->{'zip'} eq $cust_main->ship_zip );
3105     },
3106   );
3107
3108   foreach my $verify ( split(',', $verification) ) {
3109
3110     &{ $verify{$verify} }( $p, $cust_main )
3111       or return { %$info, 'error' => 'Account not found' };
3112
3113   }
3114
3115   #okay, we're verified
3116
3117   if ( $contact ) {
3118
3119     my $error = $contact->send_reset_email(
3120                             'svcnum' => ($svc_acct ? $svc_acct->svcnum : ''),
3121                           );
3122
3123     if ( $error ) {
3124       return { %$info, 'error' => $error }; #????
3125     }
3126
3127   } elsif ( $svc_acct ) {
3128
3129     #create a unique session
3130
3131     my $reset_session = {
3132       'svcnum'   => $svc_acct->svcnum,
3133       'agentnum' => $svc_acct->cust_main->agentnum,
3134     };
3135
3136     my $timeout = '1 hour'; #?
3137
3138     my $reset_session_id;
3139     do {
3140       $reset_session_id = sha512_hex(time(). {}. rand(). $$)
3141     } until ( ! defined _cache->get("reset_passwd_$reset_session_id") );
3142       #just in case
3143
3144     _cache->set( "reset_passwd_$reset_session_id", $reset_session, $timeout );
3145
3146     #email it
3147
3148     my $msgnum = $conf->config('selfservice-password_reset_msgnum',
3149                                $cust_main->agentnum);
3150     #die "selfservice-password_reset_msgnum unset" unless $msgnum;
3151     return { %$info, 'error' => "selfservice-password_reset_msgnum unset" }
3152       unless $msgnum;
3153     my $msg_template = qsearchs('msg_template', { msgnum => $msgnum } );
3154     my $error = $msg_template->send( 'cust_main'     => $cust_main,
3155                                      'object'        => $svc_acct,
3156                                      'substitutions' => {
3157                                        'session_id' => $reset_session_id,
3158                                      }
3159                                    );
3160     if ( $error ) {
3161       return { %$info, 'error' => $error }; #????
3162     }
3163
3164   }
3165
3166   return { %$info, 'error' => '' };
3167 }
3168
3169 sub check_reset_passwd {
3170   my $p = shift;
3171
3172   my $conf = new FS::Conf;
3173   my $verification = $conf->config('selfservice-password_reset_verification')
3174     or return { 'error' => 'Password resets disabled' };
3175
3176   my $reset_session = _cache->get('reset_passwd_'. $p->{'session_id'})
3177     or return { 'error' => "Can't resume session" }; #better error message
3178
3179   if ( $reset_session->{'svcnum'} ) {
3180
3181     my $svcnum = $reset_session->{'svcnum'};
3182
3183     my $svc_acct = qsearchs('svc_acct', { 'svcnum' => $svcnum } )
3184       or return { 'error' => "Service not found" };
3185
3186     $p->{'agentnum'} = $svc_acct->cust_svc->cust_pkg->cust_main->agentnum;
3187     my $info = skin_info($p);
3188
3189     return { %$info,
3190              'error'      => '',
3191              'session_id' => $p->{'session_id'},
3192              'username'   => $svc_acct->username,
3193            };
3194
3195   } elsif ( $reset_session->{'contactnum'} ) {
3196
3197     my $contactnum = $reset_session->{'contactnum'};
3198
3199     my $contact = qsearchs('contact', { 'contactnum' => $contactnum } )
3200       or return { 'error' => "Contact not found" };
3201
3202     my @contact_email = $contact->contact_email;
3203     return { 'error' => 'No contact email' } unless @contact_email;
3204
3205     my @cust_contact = grep $_->selfservice_access, $contact->cust_contact;
3206     $p->{'agentnum'} = $cust_contact[0]->cust_main->agentnum
3207       if scalar(@cust_contact) == 1;
3208     my $info = skin_info($p);
3209
3210     return { %$info,
3211              'error'      => '',
3212              'session_id' => $p->{'session_id'},
3213              'email'      => $contact_email[0]->email, #the first?
3214            };
3215
3216   } else {
3217
3218     return { 'error' => 'No svcnum or contactnum in session' }; #??
3219
3220   }
3221
3222 }
3223
3224 sub process_reset_passwd {
3225   my $p = shift;
3226
3227   my $conf = new FS::Conf;
3228   my $verification = $conf->config('selfservice-password_reset_verification')
3229     or return { 'error' => 'Password resets disabled' };
3230
3231   my $reset_session = _cache->get('reset_passwd_'. $p->{'session_id'})
3232     or return { 'error' => "Can't resume session" }; #better error message
3233
3234   my $info = '';
3235
3236   my $svc_acct = '';
3237   if ( $reset_session->{'svcnum'} ) {
3238
3239     my $svcnum = $reset_session->{'svcnum'};
3240
3241     $svc_acct = qsearchs('svc_acct', { 'svcnum' => $svcnum } )
3242       or return { 'error' => "Service not found" };
3243
3244     $p->{'agentnum'} ||= $svc_acct->cust_svc->cust_pkg->cust_main->agentnum;
3245     $info ||= skin_info($p);
3246
3247   }
3248
3249   my $contact = '';
3250   if ( $reset_session->{'contactnum'} ) {
3251
3252     my $contactnum = $reset_session->{'contactnum'};
3253
3254     $contact = qsearchs('contact', { 'contactnum' => $contactnum } )
3255       or return { 'error' => "Contact not found" };
3256
3257     my @cust_contact = grep $_->selfservice_access, $contact->cust_contact;
3258     $p->{'agentnum'} = $cust_contact[0]->cust_main->agentnum
3259       if scalar(@cust_contact) == 1;
3260     $info ||= skin_info($p);
3261
3262   }
3263
3264   return { %$info, 'error' => "New passwords don't match." }
3265     if $p->{'new_password'} ne $p->{'new_password2'};
3266
3267   return { %$info, 'error' => 'Enter new password' }
3268     unless length($p->{'new_password'});
3269
3270   if ( $svc_acct ) {
3271
3272     my $error ||= $svc_acct->is_password_allowed($p->{'new_password'})
3273               ||  $svc_acct->set_password($p->{'new_password'})
3274               ||  $svc_acct->replace();
3275
3276     return { %$info, 'error' => $error } if $error;
3277
3278     #my($label, $value) = $svc_acct->cust_svc->label;
3279     #return { 'error' => $error,
3280     #         #'label' => $label,
3281     #         #'value' => $value,
3282     #       };
3283
3284   }
3285
3286   if ( $contact ) {
3287
3288     my $error = $contact->change_password($p->{'new_password'});
3289
3290     return { %$info, 'error' => $error }; # if $error;
3291
3292   }
3293
3294   #password changed ,so remove session, don't want it reused
3295   _cache->remove($p->{'session_id'});
3296
3297   return { %$info, 'error' => '' };
3298
3299 }
3300
3301 sub list_tickets {
3302   my $p = shift;
3303   my($context, $session, $custnum) = _custoragent_session_custnum($p);
3304   return { 'error' => $session } if $context eq 'error';
3305
3306   my @tickets = ();
3307   if ( $session->{'pkgnum'} ) { 
3308
3309     #tickets for specific service with pkg-balances on
3310     my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
3311                                           'pkgnum'  => $session->{'pkgnum'} })
3312                      or return { 'error' => 'unknown package' };
3313     foreach my $cust_svc ( $cust_pkg->cust_svc ) {
3314       push @tickets, $cust_svc->tickets( $p->{status} );
3315     }
3316
3317   } else {
3318
3319     my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
3320       or return { 'error' => "unknown custnum $custnum" };
3321
3322     @tickets = $cust_main->tickets( $p->{status} );
3323   }
3324
3325   # unavoidable false laziness w/ httemplate/view/cust_main/tickets.html
3326   if ( $FS::TicketSystem::system && FS::TicketSystem->selfservice_priority ) {
3327     my $conf = new FS::Conf;
3328     my $dir = $conf->exists('ticket_system-priority_reverse') ? -1 : 1;
3329     +{ tickets => [ 
3330          sort { 
3331            (
3332              ($a->{'_selfservice_priority'} eq '') <=>
3333              ($b->{'_selfservice_priority'} eq '')
3334            ) ||
3335            ( $dir * 
3336              ($b->{'_selfservice_priority'} <=> $a->{'_selfservice_priority'})
3337            )
3338          } @tickets
3339        ]
3340     };
3341   } else {
3342     +{ tickets => \@tickets };
3343   }
3344
3345 }
3346
3347 sub create_ticket {
3348   my $p = shift;
3349   my($context, $session, $custnum) = _custoragent_session_custnum($p);
3350   return { 'error' => $session } if $context eq 'error';
3351
3352   warn "$me create_ticket: initializing ticket system\n" if $DEBUG;
3353   FS::TicketSystem->init();
3354
3355   my $conf = new FS::Conf;
3356   my $queue = $p->{'queue'}
3357               || $conf->config('ticket_system-selfservice_queueid')
3358               || $conf->config('ticket_system-default_queueid');
3359
3360   warn "$me create_ticket: creating ticket\n" if $DEBUG;
3361   my $err_or_ticket = FS::TicketSystem->create_ticket(
3362     '', #create RT session based on FS CurrentUser (fs_selfservice)
3363     'queue'   => $queue,
3364     'custnum' => $custnum,
3365     'svcnum'  => $session->{'svcnum'},
3366     map { $_ => $p->{$_} } qw( requestor cc subject message mime_type )
3367   );
3368
3369   if ( ref($err_or_ticket) ) {
3370     warn "$me create_ticket: successful: ". $err_or_ticket->id. "\n"
3371       if $DEBUG;
3372     return { 'error'     => '',
3373              'ticket_id' => $err_or_ticket->id,
3374            };
3375   } else {
3376     warn "$me create_ticket: unsuccessful: $err_or_ticket\n"
3377       if $DEBUG;
3378     return { 'error' => $err_or_ticket };
3379   }
3380
3381
3382 }
3383
3384 sub did_report {
3385   my $p = shift;
3386   my($context, $session, $custnum) = _custoragent_session_custnum($p);
3387   return { 'error' => $session } if $context eq 'error';
3388  
3389   return { error => 'requested format not implemented' } 
3390     unless ($p->{'format'} eq 'csv' || $p->{'format'} eq 'xls');
3391
3392   my $conf = new FS::Conf;
3393   my $age_threshold = 0;
3394   $age_threshold = time() - $conf->config('selfservice-recent-did-age')
3395     if ($p->{'recentonly'} && $conf->exists('selfservice-recent-did-age'));
3396
3397   my $search = { 'custnum' => $custnum };
3398   $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
3399   my $cust_main = qsearchs('cust_main', $search )
3400     or return { 'error' => "unknown custnum $custnum" };
3401
3402 # does it make more sense to just run one sql query for this instead of all the
3403 # insanity below? would increase performance greately for large data sets?
3404   my @svc_phone = ();
3405   foreach my $cust_pkg ( $cust_main->ncancelled_pkgs ) {
3406         my @part_svc = $cust_pkg->part_svc;
3407         foreach my $part_svc ( @part_svc ) {
3408             if($part_svc->svcdb eq 'svc_phone'){
3409                 my @cust_pkg_svc = @{$part_svc->cust_pkg_svc};
3410                 foreach my $cust_pkg_svc ( @cust_pkg_svc ) {
3411                     push @svc_phone, $cust_pkg_svc->svc_x
3412                         if $cust_pkg_svc->date_inserted >= $age_threshold;
3413                 }
3414             }
3415         }
3416   }
3417
3418   my $csv;
3419   my $xls;
3420   my($xls_r,$xls_c) = (0,0);
3421   my $xls_workbook;
3422   my $content = '';
3423   my @fields = qw( countrycode phonenum pin sip_password phone_name );
3424   if($p->{'format'} eq 'csv') {
3425     $csv = new Text::CSV_XS { 'always_quote' => 1,
3426                                  'eol'          => "\n",
3427                                 };
3428     return { 'error' => 'Unable to create CSV' } unless $csv->combine(@fields);
3429     $content .= $csv->string;
3430   }
3431   elsif($p->{'format'} eq 'xls') {
3432     my $XLS1 = new IO::Scalar \$content;
3433     $xls_workbook = Spreadsheet::WriteExcel->new($XLS1) 
3434         or return { 'error' => "Error opening .xls file: $!" };
3435     $xls = $xls_workbook->add_worksheet('DIDs');
3436     foreach ( @fields ) {
3437         $xls->write(0,$xls_c++,$_);
3438     }
3439     $xls_r++;
3440   }
3441
3442   foreach my $svc_phone ( @svc_phone ) {
3443     my @cols = map { $svc_phone->$_ } @fields;
3444     if($p->{'format'} eq 'csv') {
3445         return { 'error' => 'Unable to create CSV' } 
3446             unless $csv->combine(@cols);
3447         $content .= $csv->string;
3448     }
3449     elsif($p->{'format'} eq 'xls') {
3450         $xls_c = 0;
3451         foreach ( @cols ) {
3452             $xls->write($xls_r,$xls_c++,$_);
3453         }
3454         $xls_r++;
3455     }
3456   }
3457
3458   $xls_workbook->close() if $p->{'format'} eq 'xls';
3459   
3460   { content => $content, format => $p->{'format'}, };
3461 }
3462
3463 sub get_ticket {
3464   my $p = shift;
3465   my($context, $session, $custnum) = _custoragent_session_custnum($p);
3466   return { 'error' => $session } if $context eq 'error';
3467
3468 #  warn "$me get_ticket: initializing ticket system\n" if $DEBUG;
3469 #  FS::TicketSystem->init();
3470 #  return { 'error' => 'get_ticket configuration error' }
3471 #    if $FS::TicketSystem::system ne 'RT_Internal';
3472
3473   # check existence and ownership as part of this
3474   warn "$me get_ticket: fetching ticket\n" if $DEBUG;
3475   my $rt_session = FS::TicketSystem->session('');
3476   my $Ticket = FS::TicketSystem->get_ticket_object(
3477     $rt_session, 
3478     ticket_id => $p->{'ticket_id'},
3479     custnum => $custnum
3480   );
3481   return { 'error' => 'ticket not found' } if !$Ticket;
3482
3483   if ( length( $p->{'subject'} || '' ) ) {
3484     # subject change
3485     if ( $p->{'subject'} ne $Ticket->Subject ) {
3486       my ($val, $msg) = $Ticket->SetSubject($p->{'subject'});
3487       return { 'error' => "unable to set subject: $msg" } if !$val;
3488     }
3489   }
3490
3491   if(length($p->{'reply'})) {
3492     my @err_or_res = FS::TicketSystem->correspond_ticket(
3493       $rt_session,
3494       'ticket_id' => $p->{'ticket_id'},
3495       'content' => $p->{'reply'},
3496     );
3497
3498     return { 'error' => 'unable to reply to ticket' } 
3499     unless ( $err_or_res[0] != 0 && defined $err_or_res[2] );
3500   }
3501
3502   warn "$me get_ticket: getting ticket history\n" if $DEBUG;
3503   my $err_or_ticket = FS::TicketSystem->get_ticket(
3504     $rt_session,
3505     'ticket_id' => $p->{'ticket_id'},
3506   );
3507
3508   if ( !ref($err_or_ticket) ) { # there is no way this should ever happen
3509     warn "$me get_ticket: unsuccessful: $err_or_ticket\n"
3510       if $DEBUG;
3511     return { 'error' => $err_or_ticket };
3512   }
3513
3514   my @custs = @{$err_or_ticket->{'custs'}};
3515   my @txns = @{$err_or_ticket->{'txns'}};
3516   my @filtered_txns;
3517
3518   # superseded by check in get_ticket_object
3519   #return { 'error' => 'invalid ticket requested' } 
3520   #unless grep($_ eq $custnum, @custs);
3521
3522   foreach my $txn ( @txns ) {
3523     push @filtered_txns, $txn 
3524     if ($txn->{'type'} eq 'EmailRecord' 
3525       || $txn->{'type'} eq 'Correspond'
3526       || $txn->{'type'} eq 'Create');
3527   }
3528
3529   warn "$me get_ticket: successful: \n"
3530   if $DEBUG;
3531   return { 'error'     => '',
3532     'transactions' => \@filtered_txns,
3533     'ticket_fields' => $err_or_ticket->{'fields'},
3534     'ticket_id' => $p->{'ticket_id'},
3535   };
3536 }
3537
3538 sub adjust_ticket_priority {
3539   my $p = shift;
3540   my($context, $session, $custnum) = _custoragent_session_custnum($p);
3541   return { 'error' => $session } if $context eq 'error';
3542
3543 #  warn "$me adjust_ticket_priority: initializing ticket system\n" if $DEBUG;
3544 #  FS::TicketSystem->init;
3545   my $ss_priority = FS::TicketSystem->selfservice_priority;
3546
3547   return { 'error' => 'adjust_ticket_priority configuration error' }
3548     if $FS::TicketSystem::system ne 'RT_Internal'
3549       or !$ss_priority;
3550
3551   my $values = $p->{'values'}; #hashref, id => priority value
3552   my %ticket_error;
3553
3554   foreach my $id (keys %$values) {
3555     warn "$me adjust_ticket_priority: fetching ticket $id\n" if $DEBUG;
3556     my $Ticket = FS::TicketSystem->get_ticket_object('',
3557       'ticket_id' => $id,
3558       'custnum'   => $custnum,
3559     );
3560     if ( !$Ticket ) {
3561       $ticket_error{$id} = 'ticket not found';
3562       next;
3563     }
3564     
3565   # RT API stuff--would we gain anything by wrapping this in FS::TicketSystem?
3566   # We're not going to implement it for RT_External.
3567     my $old_value = $Ticket->FirstCustomFieldValue($ss_priority);
3568     my $new_value = $values->{$id};
3569     next if $old_value eq $new_value;
3570
3571     warn "$me adjust_ticket_priority: updating ticket $id\n" if $DEBUG;
3572
3573     # AddCustomFieldValue works fine (replacing any existing value) if it's 
3574     # a single-valued custom field, which it should be.  If it's not, you're 
3575     # doing something wrong.
3576     my ($val, $msg);
3577     if ( length($new_value) ) {
3578       ($val, $msg) = $Ticket->AddCustomFieldValue( 
3579         Field => $ss_priority,
3580         Value => $new_value,
3581       );
3582     }
3583     else {
3584       ($val, $msg) = $Ticket->DeleteCustomFieldValue(
3585         Field => $ss_priority,
3586         Value => $old_value,
3587       );
3588     }
3589
3590     $ticket_error{$id} = $msg if !$val;
3591     warn "$me adjust_ticket_priority: $id: $msg\n" if $DEBUG and !$val;
3592   }
3593   return { 'error' => '',
3594            'ticket_error' => \%ticket_error,
3595            %{ customer_info($p) } # send updated customer info back
3596          }
3597 }
3598
3599 #--
3600
3601 sub _custoragent_session_custnum {
3602   my $p = shift;
3603
3604   my($context, $session, $custnum);
3605   if ( $p->{'session_id'} ) {
3606
3607     $context = 'customer';
3608     $session = _cache->get($p->{'session_id'})
3609       or return ( 'error' => "Can't resume session" ); #better error message
3610     $custnum = $session->{'custnum'};
3611
3612   } elsif ( $p->{'agent_session_id'} ) {
3613
3614     $context = 'agent';
3615     my $agent_cache = new FS::ClientAPI_SessionCache( {
3616       'namespace' => 'FS::ClientAPI::Agent',
3617     } );
3618     $session = $agent_cache->get($p->{'agent_session_id'})
3619       or return ( 'error' => "Can't resume session" ); #better error message
3620     $custnum = $p->{'custnum'};
3621
3622   } else {
3623     $context = 'error';
3624     return ( 'error' => "Can't resume session" ); #better error message
3625   }
3626
3627   ($context, $session, $custnum);
3628
3629 }
3630
3631 1;
3632