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