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