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