RT# 83147 - Added new error message when email does not match because of case sensitivity
[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 => 'Username '.$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   # look for stored cust_payby info
905   #   v3 to v4 upgrade would break change_pay because change_pay does not send payment_payby
906   #   so for change_pay to work need to search for all allowed paybys and grab default payment account
907   my @search_payby = ();
908   @search_payby = ($p->{'payment_payby'} eq 'CARD') ? ('CARD','DCRD') : ('CHEK','DCHK')
909     if ($p->{'payment_payby'} =~ /^(CARD|CHEK)$/);
910
911   my ($cust_payby) = $cust_main->cust_payby(@search_payby);
912   if ($cust_payby) {
913     $return{payby} = $cust_payby->payby;
914     $return{payname} = $cust_payby->payname
915                          || ( $cust_main->first. ' '. $cust_main->get('last') );
916     $return{custpaybynum} = $cust_payby->custpaybynum;
917
918     if ( $cust_payby->payby =~ /^(CARD|DCRD)$/ ) {
919       $return{card_type} = cardtype($cust_payby->payinfo);
920       $return{payinfo} = $cust_payby->paymask;
921
922       @return{'month', 'year'} = $cust_payby->paydate_monthyear;
923
924     }
925
926     if ( $cust_payby->payby =~ /^(CHEK|DCHK)$/ ) {
927       my ($payinfo1, $payinfo2) = split '@', $cust_payby->paymask;
928       $return{payinfo1} = $payinfo1;
929       $return{payinfo2} = $payinfo2;
930       $return{paytype}  = $cust_payby->paytype;
931       $return{paystate} = $cust_payby->paystate;
932       $return{payname}  = $cust_payby->payname; # override 'first/last name' default from above, if any.  Is instution-name here.  (#15819)
933     }
934   }
935
936   if ( $conf->config('prepayment_discounts-credit_type') ) {
937     #need to eval?
938     $return{discount_terms_hash} = { $cust_main->discount_terms_hash };
939   }
940
941   #doubleclick protection
942   my $_date = time;
943   $return{payunique} = "webui-MyAccount-$_date-$$-". rand() * 2**32; #new
944   $return{paybatch} = $return{payunique};  #back compat
945
946   $return{credit_card_surcharge_percentage} = $conf->config('credit-card-surcharge-percentage', $cust_main->agentnum);
947   $return{credit_card_surcharge_flatfee} = $conf->config('credit-card-surcharge-flatfee', $cust_main->agentnum);
948
949   # A value for 'payby' must be defined in %return
950   $return{payby} = $return{paybys}->[0]
951     if !$return{payby}
952     && ref $return{paybys}
953     && scalar @{ $return{paybys} };
954
955   return { 'error' => '',
956            %return,
957          };
958
959 }
960
961 #some false laziness with httemplate/process/payment.cgi - look there for
962 #ACH and CVV support stuff
963
964 sub validate_payment {
965   my $p = shift;
966
967   my $session = _cache->get($p->{'session_id'})
968     or return { 'error' => "Can't resume session" }; #better error message
969
970   my $custnum = $session->{'custnum'};
971
972   my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
973     or return { 'error' => "unknown custnum $custnum" };
974
975   $p->{'amount'} =~ /^\s*(\d+(\.\d{2})?)\s*$/
976     or return { 'error' => gettext('illegal_amount') };
977   my $amount = $1;
978   return { error => 'Amount must be greater than 0' } unless $amount > 0;
979
980   #false laziness w/tr-amount_fee.html, but we don't want selfservice users
981   #changing the hidden form values
982   my $conf = new FS::Conf;
983   my $fee_display = $conf->config('selfservice_process-display') || 'add';
984   my $fee_pkgpart = $conf->config('selfservice_process-pkgpart', $cust_main->agentnum);
985   my $fee_skip_first = $conf->exists('selfservice_process-skip_first');
986   if ( $fee_display eq 'add'
987          and $fee_pkgpart
988          and ! $fee_skip_first || scalar($cust_main->cust_pay)
989      )
990   {
991     my $fee_pkg = qsearchs('part_pkg', { pkgpart=>$fee_pkgpart } );
992     $amount = sprintf('%.2f', $amount + $fee_pkg->option('setup_fee') );
993   }
994
995   $p->{'discount_term'} =~ /^\s*(\d*)\s*$/
996     or return { 'error' => gettext('illegal_discount_term'). ': '. $p->{'discount_term'} };
997   my $discount_term = $1;
998
999   $p->{'payname'} =~ /^([\w \,\.\-\']+)$/
1000     or return { 'error' => gettext('illegal_name'). " payname: ". $p->{'payname'} };
1001   my $payname = $1;
1002
1003   $p->{'payunique'} =~ /^([\w \!\@\#\$\%\&\(\)\-\+\;\:\'\"\,\.\?\/\=]*)$/
1004     or return { 'error' => gettext('illegal_text'). " payunique: ". $p->{'payunique'} };
1005   my $payunique = $1;
1006
1007   $p->{'paybatch'} =~ /^([\w \!\@\#\$\%\&\(\)\-\+\;\:\'\"\,\.\?\/\=]*)$/
1008     or return { 'error' => gettext('illegal_text'). " paybatch: ". $p->{'paybatch'} };
1009   my $paybatch = $1;
1010
1011   $payunique = $paybatch if ! length($payunique) && length($paybatch);
1012
1013   $p->{'payby'} ||= 'CARD';
1014   $p->{'payby'} =~ /^([A-Z]{4})$/
1015     or return { 'error' => "illegal_payby " . $p->{'payby'} };
1016   my $payby = $1;
1017
1018   #false laziness w/process/payment.cgi
1019   my $payinfo;
1020   my $paycvv = '';
1021   my $replace_cust_payby;
1022   if ( $payby eq 'CHEK' || $payby eq 'DCHK' ) {
1023   
1024     $p->{'payinfo1'} =~ /^([\dx]+)$/
1025       or return { 'error' => "illegal account number ". $p->{'payinfo1'} };
1026     my $payinfo1 = $1;
1027      $p->{'payinfo2'} =~ /^([\dx]+)$/
1028       or return { 'error' => "illegal ABA/routing number ". $p->{'payinfo2'} };
1029     my $payinfo2 = $1;
1030     $payinfo = $payinfo1. '@'. $payinfo2;
1031
1032     my $achonfile = 0;
1033     foreach my $cust_payby ($cust_main->cust_payby('CHEK','DCHK')) {
1034       if ( $cust_payby->paymask eq $payinfo ) {
1035         $payinfo = $cust_payby->payinfo;
1036         $replace_cust_payby = $cust_payby;
1037         $achonfile = 1;
1038         last;
1039       }
1040     }
1041
1042     if ($conf->exists('selfservice-ACH_info_readonly') && !$achonfile) {
1043       return { 'error' => "You are not allowed to change your payment information." };
1044     }
1045    
1046   } elsif ( $payby eq 'CARD' || $payby eq 'DCRD' ) {
1047    
1048     $payinfo = $p->{'payinfo'};
1049
1050     my $onfile = 0;
1051
1052     #more intelligent matching will be needed here if you change
1053     #card_masking_method and don't remove existing paymasks
1054     foreach my $cust_payby ($cust_main->cust_payby('CARD','DCRD')) {
1055       if ( $cust_payby->paymask eq $payinfo ) {
1056         $payinfo = $cust_payby->payinfo;
1057         $replace_cust_payby = $cust_payby;
1058         $onfile = 1;
1059         last;
1060       }
1061     }
1062
1063     $payinfo =~ s/\D//g;
1064     $payinfo =~ /^(\d{13,19}|\d{8,9})$/
1065       or return { 'error' => gettext('invalid_card') }; # . ": ". $self->payinfo
1066     $payinfo = $1;
1067
1068     validate($payinfo)
1069       or return { 'error' => gettext('invalid_card') }; # . ": ". $self->payinfo
1070     return { 'error' => gettext('unknown_card_type') }
1071       if !$cust_main->tokenized($payinfo) && cardtype($payinfo) eq "Unknown";
1072
1073     if ( length($p->{'paycvv'}) && $p->{'paycvv'} !~ /^\s*$/ ) {
1074       if ( cardtype($payinfo) eq 'American Express card' ) {
1075         $p->{'paycvv'} =~ /^\s*(\d{4})\s*$/
1076           or return { 'error' => "CVV2 (CID) for American Express cards is four digits." };
1077         $paycvv = $1;
1078       } else {
1079         $p->{'paycvv'} =~ /^\s*(\d{3})\s*$/
1080           or return { 'error' => "CVV2 (CVC2/CID) is three digits." };
1081         $paycvv = $1;
1082       }
1083     } elsif ( $conf->exists('selfservice-onfile_require_cvv') ) {
1084       return { 'error' => 'CVV2 is required' };
1085     } elsif ( !$onfile && $conf->exists('selfservice-require_cvv') ) {
1086       return { 'error' => 'CVV2 is required' };
1087     }
1088   
1089   } else {
1090     die "unknown payby $payby";
1091   }
1092
1093   my %payby2fields = (
1094     'CARD' => [ qw( paystart_month paystart_year payissue payip
1095                     address1 address2 city state zip country    ) ],
1096     'CHEK' => [ qw( ss paytype paystate stateid stateid_state payip ) ],
1097   );
1098
1099   my %replace = ( 'replace' => $replace_cust_payby, );
1100
1101   my $card_type = '';
1102   $card_type = cardtype($payinfo) if $payby eq 'CARD';
1103
1104   { 
1105     'cust_main'      => $cust_main, #XXX or just custnum??
1106     'amount'         => sprintf('%.2f', $amount),
1107     'payby'          => $payby,
1108     'payinfo'        => $payinfo,
1109     'paymask'        => FS::payinfo_Mixin->mask_payinfo( $payby, $payinfo ),
1110     'card_type'      => $card_type,
1111     'paydate'        => $p->{'year'}. '-'. $p->{'month'}. '-01',
1112     'paydate_pretty' => $p->{'month'}. ' / '. $p->{'year'},
1113     'month'          => $p->{'month'},
1114     'year'           => $p->{'year'},
1115     'payname'        => $payname,
1116     'payunique'      => $payunique,
1117     'paybatch'       => $paybatch,
1118     'paycvv'         => $paycvv,
1119     'payname'        => $payname,
1120     'discount_term'  => $discount_term,
1121     'pkgnum'         => $session->{'pkgnum'},
1122     %replace,
1123     map { $_ => $p->{$_} } ( @{ $payby2fields{$payby} },
1124                              qw( save auto ),
1125                            )
1126   };
1127
1128 }
1129
1130 sub store_payment {
1131   my $p = shift;
1132
1133   my $validate = validate_payment($p);
1134   return $validate if $validate->{'error'};
1135
1136   my $conf = new FS::Conf;
1137   my $timeout = $conf->config('selfservice-session_timeout') || '1 hour'; #?
1138   _cache->set( 'payment_'.$p->{'session_id'}, $validate, $timeout );
1139
1140   +{ map { $_=>$validate->{$_} }
1141       qw( card_type paymask payname paydate_pretty month year amount
1142           address1 address2 city state zip country
1143         )
1144   };
1145
1146 }
1147
1148 sub process_stored_payment {
1149   my $p = shift;
1150
1151   my $session_id = $p->{'session_id'};
1152
1153   my $payment_info = _cache->get( "payment_$session_id" )
1154     or return { 'error' => "Can't resume session" }; #better error message
1155
1156   do_process_payment($payment_info);
1157
1158 }
1159
1160 sub process_payment {
1161   my $p = shift;
1162
1163   my $payment_info = validate_payment($p);
1164   return $payment_info if $payment_info->{'error'};
1165
1166   do_process_payment($payment_info);
1167
1168 }
1169
1170 sub do_process_payment {
1171   my $validate = shift;
1172
1173   my $cust_main = $validate->{'cust_main'};
1174
1175   my $amount = delete $validate->{'amount'};
1176   my $paynum = '';
1177
1178   my $payby = delete $validate->{'payby'};
1179
1180   if ( $validate->{'save'} ) {
1181
1182     my %saveopt;
1183     foreach my $field ( qw( auto payinfo paymask payname payip ) ) {
1184       $saveopt{$field} = $validate->{$field};
1185     }
1186
1187     if ( $payby eq 'CARD' ) {
1188       my $bill_location = FS::cust_location->new({
1189           map { $_ => $validate->{$_} } 
1190           qw(address1 address2 city state country zip)
1191       });
1192       $saveopt{'bill_location'} = $bill_location;
1193       foreach my $field ( qw( paydate paystart_month paystart_year payissue ) ) {
1194         $saveopt{$field} = $validate->{$field};
1195       }
1196     } else {
1197       # stateid/stateid_state won't be saved, might be broken as of 4.x
1198       foreach my $field ( qw( paytype paystate ) ) {
1199         $saveopt{$field} = $validate->{$field};
1200       }
1201     }
1202
1203     my $error = $cust_main->save_cust_payby(
1204       'payment_payby' => $payby,
1205       'replace'       => $validate->{'replace'}, # cust_payby object to replace
1206       %saveopt
1207     );
1208
1209     if ( $error ) {
1210       #no, this causes customers to process their payments again
1211       #return { 'error' => $error };
1212       #XXX just warn verosely for now so i can figure out how these happen in
1213       # the first place, eventually should redirect them to the "change
1214       #address" page but indicate if the payment processed?
1215       delete($validate->{'payinfo'}); #don't want to log this!
1216       warn "WARNING: error changing customer info when processing payment (not returning to customer as a processing error): $error\n".
1217            "PAYBY: $payby\n".
1218            "SAVEOPT: ".Dumper(\%saveopt)."\n".
1219            "CUST_MAIN: ". Dumper($cust_main)."\n".
1220            "PACKET: ". Dumper($validate)."\n";
1221     }
1222   }
1223
1224   my $error = $cust_main->realtime_bop( $FS::payby::payby2bop{$payby}, $amount,
1225     'quiet'       => 1,
1226     'manual'      => 1,
1227     'selfservice' => 1,
1228     'paynum_ref'  => \$paynum,
1229     %$validate,
1230   );
1231   return { 'error' => $error } if $error;
1232
1233   #no error, so order the fee package if applicable...
1234   my $conf = new FS::Conf;
1235   my $fee_pkgpart = $conf->config('selfservice_process-pkgpart', $cust_main->agentnum);
1236   my $fee_skip_first = $conf->exists('selfservice_process-skip_first');
1237   
1238   if ( $fee_pkgpart and ! $fee_skip_first || scalar($cust_main->cust_pay) ) {
1239
1240     my $cust_pkg = new FS::cust_pkg { 'pkgpart' => $fee_pkgpart };
1241
1242     $error = $cust_main->order_pkg( 'cust_pkg' => $cust_pkg );
1243     return { 'error' => "payment processed successfully, but error ordering fee: $error" }
1244       if $error;
1245
1246     #and generate an invoice for it now too
1247     $error = $cust_main->bill( 'pkg_list' => [ $cust_pkg ] );
1248     return { 'error' => "payment processed and fee ordered successfully, but error billing fee: $error" }
1249       if $error;
1250
1251   }
1252
1253   $cust_main->apply_payments;
1254
1255   my $cust_pay = '';
1256   my $receipt_html = '';
1257   if ($paynum) {
1258       # currently supported for realtime CC only; send receipt data to SS
1259       $cust_pay = qsearchs('cust_pay', { 'paynum' => $paynum } );
1260       if($cust_pay) {
1261         $receipt_html = qq!
1262 <TABLE BGCOLOR="#cccccc" BORDER=0 CELLSPACING=2>
1263
1264 <TR>
1265   <TD ALIGN="right">Payment#</TD>
1266   <TD BGCOLOR="#FFFFFF"><B>! . $cust_pay->paynum . qq!</B></TD>
1267 </TR>
1268
1269 <TR>
1270   <TD ALIGN="right">Date</TD>
1271
1272   <TD BGCOLOR="#FFFFFF"><B>! . 
1273         time2str("%a&nbsp;%b&nbsp;%o,&nbsp;%Y&nbsp;%r", $cust_pay->_date)
1274                                                             . qq!</B></TD>
1275 </TR>
1276
1277
1278 <TR>
1279   <TD ALIGN="right">Amount</TD>
1280   <TD BGCOLOR="#FFFFFF"><B>! . sprintf('%.2f', $cust_pay->paid) . qq!</B></TD>
1281
1282 </TR>
1283
1284 <TR>
1285   <TD ALIGN="right">Payment method</TD>
1286   <TD BGCOLOR="#FFFFFF"><B>! . $cust_pay->payby_name .' #'. $cust_pay->paymask
1287                                                                 . qq!</B></TD>
1288 </TR>
1289
1290 </TABLE>
1291 !;
1292       }
1293   }
1294
1295   if ( $cust_pay ) {
1296
1297     return {
1298       'error'        => '',
1299       'amount'       => sprintf('%.2f', $cust_pay->paid),
1300       'date'         => $cust_pay->_date,
1301       'date_pretty'  => time2str('%Y-%m-%d', $cust_pay->_date),
1302       'time_pretty'  => time2str('%T', $cust_pay->_date),
1303       'auth_num'     => $cust_pay->auth,
1304       'order_num'    => $cust_pay->order_number,
1305       'receipt_html' => $receipt_html,
1306     };
1307
1308   } else {
1309
1310     return {
1311       'error'        => '',
1312       'receipt_html' => '',
1313     };
1314
1315   }
1316
1317 }
1318
1319 sub realtime_collect {
1320   my $p = shift;
1321
1322   my $session = _cache->get($p->{'session_id'})
1323     or return { 'error' => "Can't resume session" }; #better error message
1324
1325   my $custnum = $session->{'custnum'};
1326
1327   my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1328     or return { 'error' => "unknown custnum $custnum" };
1329
1330   my $amount;
1331   if ( $p->{'amount'} ) {
1332     $amount = $p->{'amount'};
1333   }
1334   elsif ( $session->{'pkgnum'} ) {
1335     $amount = $cust_main->balance_pkgnum( $session->{'pkgnum'} );
1336   }
1337   else {
1338     $amount = $cust_main->balance;
1339   }
1340
1341   my $error = $cust_main->realtime_collect(
1342     'method'     => $p->{'method'},
1343     'amount'     => $amount,
1344     'pkgnum'     => $session->{'pkgnum'},
1345     'session_id' => $p->{'session_id'},
1346     'apply'      => 1,
1347     'selfservice'=> 1,
1348   );
1349   return { 'error' => $error } unless ref( $error );
1350
1351   return { 'error' => '', amount => $amount, %$error };
1352 }
1353
1354 sub start_thirdparty {
1355   my $p = shift;
1356   my $session = _cache->get($p->{'session_id'})
1357     or return { 'error' => "Can't resume session" }; #better error message
1358   my $custnum = $session->{'custnum'};
1359   my $cust_main = FS::cust_main->by_key($custnum);
1360   
1361   my $amount = $p->{'amount'}
1362     or return { error => 'no amount' };
1363
1364   my $result = $cust_main->create_payment(
1365     'method'      => $p->{'method'},
1366     'amount'      => $p->{'amount'},
1367     'pkgnum'      => $session->{'pkgnum'},
1368     'session_id'  => $p->{'session_id'},
1369   );
1370   
1371   if ( ref($result) ) { # hashref or error
1372     return $result;
1373   } else {
1374     return { error => $result };
1375   }
1376 }
1377
1378 sub finish_thirdparty {
1379   my $p = shift;
1380   my $session_id = delete $p->{'session_id'};
1381   my $session = _cache->get($session_id)
1382     or return { 'error' => "Can't resume session" };
1383   my $custnum = $session->{'custnum'};
1384   my $cust_main = FS::cust_main->by_key($custnum);
1385
1386   if ( $p->{_cancel} ) {
1387     # customer backed out of making a payment
1388     return $cust_main->cancel_payment( $session_id );
1389   }
1390   my $result = $cust_main->execute_payment( $session_id, %$p );
1391   if ( ref($result) ) {
1392     return $result;
1393   } else {
1394     return { error => $result };
1395   }
1396 }
1397
1398 sub process_payment_order_pkg {
1399   my $p = shift;
1400
1401   my $hr = process_payment($p);
1402   return $hr if $hr->{'error'};
1403
1404   order_pkg($p);
1405 }
1406
1407 sub process_payment_order_renew {
1408   my $p = shift;
1409
1410   my $hr = process_payment($p);
1411   return $hr if $hr->{'error'};
1412
1413   order_renew($p);
1414 }
1415
1416 sub process_prepay {
1417
1418   my $p = shift;
1419
1420   my $session = _cache->get($p->{'session_id'})
1421     or return { 'error' => "Can't resume session" }; #better error message
1422
1423   my %return;
1424
1425   my $custnum = $session->{'custnum'};
1426
1427   my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1428     or return { 'error' => "unknown custnum $custnum" };
1429
1430   my( $amount, $seconds, $upbytes, $downbytes, $totalbytes ) = ( 0, 0, 0, 0, 0 );
1431   my $error = $cust_main->recharge_prepay( $p->{'prepaid_cardnum'},
1432                                            \$amount,
1433                                            \$seconds,
1434                                            \$upbytes,
1435                                            \$downbytes,
1436                                            \$totalbytes,
1437                                          );
1438
1439   return { 'error' => $error } if $error;
1440
1441   return { 'error'     => '',
1442            'amount'    => $amount,
1443            'seconds'   => $seconds,
1444            'duration'  => duration_exact($seconds),
1445            'upbytes'   => $upbytes,
1446            'upload'    => FS::UI::bytecount::bytecount_unexact($upbytes),
1447            'downbytes' => $downbytes,
1448            'download'  => FS::UI::bytecount::bytecount_unexact($downbytes),
1449            'totalbytes'=> $totalbytes,
1450            'totalload' => FS::UI::bytecount::bytecount_unexact($totalbytes),
1451          };
1452
1453 }
1454
1455 sub invoice {
1456   my $p = shift;
1457   my $session = _cache->get($p->{'session_id'})
1458     or return { 'error' => "Can't resume session" }; #better error message
1459
1460   my $custnum = $session->{'custnum'};
1461
1462   my $invnum = $p->{'invnum'};
1463
1464   my $cust_bill = qsearchs('cust_bill', { 'invnum'  => $invnum,
1465                                           'custnum' => $custnum } )
1466     or return { 'error' => "Can't find invnum" };
1467
1468   #my %return;
1469
1470   return { 'error'        => '',
1471            'invnum'       => $invnum,
1472            'invoice_text' => join('', $cust_bill->print_text ),
1473            'invoice_html' => $cust_bill->print_html( { unsquelch_cdr => 1 } ),
1474          };
1475
1476 }
1477
1478 sub invoice_pdf {
1479   my $p = shift;
1480   my $session = _cache->get($p->{'session_id'})
1481     or return { 'error' => "Can't resume session" }; #better error message
1482
1483   my $custnum = $session->{'custnum'};
1484
1485   my $invnum = $p->{'invnum'};
1486
1487   my $cust_bill = qsearchs('cust_bill', { 'invnum'  => $invnum,
1488                                           'custnum' => $custnum } )
1489     or return { 'error' => "Can't find invnum" };
1490
1491   #my %return;
1492
1493   return { 'error'       => '',
1494            'invnum'      => $invnum,
1495            'invoice_pdf' => $cust_bill->print_pdf({
1496                               'unsquelch_cdr' => 1,
1497                               'locale'        => $p->{'locale'},
1498                             }),
1499          };
1500
1501 }
1502
1503 sub legacy_invoice {
1504   my $p = shift;
1505   my $session = _cache->get($p->{'session_id'})
1506     or return { 'error' => "Can't resume session" }; #better error message
1507
1508   my $custnum = $session->{'custnum'};
1509
1510   my $legacyinvnum = $p->{'legacyinvnum'};
1511
1512   my %hash = (
1513     'legacyinvnum' => $legacyinvnum,
1514     'custnum'      => $custnum,
1515   );
1516
1517   my $legacy_cust_bill =
1518          qsearchs('legacy_cust_bill', { %hash, 'locale' => $p->{'locale'} } )
1519       || qsearchs('legacy_cust_bill', \%hash )
1520     or return { 'error' => "Can't find legacyinvnum" };
1521
1522   #my %return;
1523
1524   return { 'error'        => '',
1525            'legacyinvnum' => $legacyinvnum,
1526            'legacyid'     => $legacy_cust_bill->legacyid,
1527            'invoice_html' => $legacy_cust_bill->content_html,
1528          };
1529
1530 }
1531
1532 sub legacy_invoice_pdf {
1533   my $p = shift;
1534   my $session = _cache->get($p->{'session_id'})
1535     or return { 'error' => "Can't resume session" }; #better error message
1536
1537   my $custnum = $session->{'custnum'};
1538
1539   my $legacyinvnum = $p->{'legacyinvnum'};
1540
1541   my $legacy_cust_bill = qsearchs('legacy_cust_bill', {
1542     'legacyinvnum' => $legacyinvnum,
1543     'custnum'      => $custnum,
1544   }) or return { 'error' => "Can't find legacyinvnum" };
1545
1546   #my %return;
1547
1548   return { 'error'        => '',
1549            'legacyinvnum' => $legacyinvnum,
1550            'legacyid'     => $legacy_cust_bill->legacyid,
1551            'invoice_pdf'  => $legacy_cust_bill->content_pdf,
1552          };
1553
1554 }
1555
1556 sub invoice_logo {
1557   my $p = shift;
1558
1559   #sessioning for this?  how do we get the session id to the backend invoice
1560   # template so it can add it to the link, blah
1561
1562   my $agentnum = '';
1563   if ( $p->{'invnum'} ) {
1564     my $cust_bill = qsearchs('cust_bill', { 'invnum' => $p->{'invnum'} } )
1565       or return { 'error' => 'unknown invnum' };
1566     $agentnum = $cust_bill->cust_main->agentnum;
1567   }
1568
1569   my $templatename = $p->{'template'} || $p->{'templatename'};
1570
1571   #false laziness-ish w/view/cust_bill-logo.cgi
1572
1573   my $conf = new FS::Conf;
1574   if ( $templatename =~ /^([^\.\/]*)$/ && $conf->exists("logo_$1.png") ) {
1575     $templatename = "_$1";
1576   } else {
1577     $templatename = '';
1578   }
1579
1580   my $filename = "logo$templatename.png";
1581
1582   return { 'error'        => '',
1583            'logo'         => $conf->config_binary($filename, $agentnum),
1584            'content_type' => 'image/png', #should allow gif, jpg too
1585          };
1586 }
1587
1588 sub list_invoices {
1589   my $p = shift;
1590   my $session = _cache->get($p->{'session_id'})
1591     or return { 'error' => "Can't resume session" }; #better error message
1592
1593   my $custnum = $session->{'custnum'};
1594
1595   my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1596     or return { 'error' => "unknown custnum $custnum" };
1597
1598   my $conf = new FS::Conf;
1599
1600   my @legacy_cust_bill = $cust_main->legacy_cust_bill;
1601
1602   my @cust_bill = grep ! $_->hide, $cust_main->cust_bill;
1603
1604   my $balance = 0;
1605   my $invoices = [
1606     map {
1607       #not super efficient, we also run cust_bill_pay/cust_credited inside owed
1608       my @payments_and_credits = sort {$b->_date <=> $a->_date} ($_->cust_bill_pay,$_->cust_credited);
1609       my $owed = $_->owed;
1610       $balance += $owed;
1611       +{ 'invnum'       => $_->invnum,
1612          '_date'        => $_->_date,
1613          'date'         => time2str("%b %o, %Y", $_->_date),
1614          'date_short'   => time2str("%m-%d-%Y",  $_->_date),
1615          'previous'     => sprintf('%.2f', ($_->previous)[0]),
1616          'charged'      => sprintf('%.2f', $_->charged),
1617          'owed'         => sprintf('%.2f', $owed),
1618          'balance'      => sprintf('%.2f', $balance),
1619          'lastpay'      => @payments_and_credits 
1620                            ? time2str("%b %o, %Y", $payments_and_credits[0]->_date)
1621                            : '',
1622       }
1623     } @cust_bill
1624   ];
1625
1626   return  { 'error'       => '',
1627             'balance'     => $cust_main->balance,
1628             'money_char'  => $conf->config("money_char") || '$',
1629             'invoices'    => $invoices,
1630             'legacy_invoices' => [
1631               map {
1632                     +{ 'legacyinvnum' => $_->legacyinvnum,
1633                        'legacyid'     => $_->legacyid,
1634                        '_date'        => $_->_date,
1635                        'date'         => time2str("%b %o, %Y", $_->_date),
1636                        'date_short'   => time2str("%m-%d-%Y",  $_->_date),
1637                        'charged'      => sprintf('%.2f', $_->charged),
1638                        'has_content'  => (    length($_->content_pdf)
1639                                            || length($_->content_html) ),
1640                      }
1641                   }
1642                   @legacy_cust_bill
1643             ],
1644           };
1645 }
1646
1647 sub list_payments {
1648   my $p = shift;
1649   my $session = _cache->get($p->{'session_id'})
1650     or return { 'error' => "Can't resume session" }; #better error message
1651
1652   my $custnum = $session->{'custnum'};
1653
1654   my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1655     or return { 'error' => "unknown custnum $custnum" };
1656
1657   return  { 'error'       => '',
1658             'balance'     => $cust_main->balance,
1659             'money_char'  => FS::Conf->new->config("money_char") || '$',
1660             'payments'    => [ map $_->SSAPI_getinfo, $cust_main->cust_pay ],
1661           };
1662 }
1663
1664 sub payment_receipt {
1665   my $p = shift;
1666   my $session = _cache->get($p->{'session_id'})
1667     or return { 'error' => "Can't resume session" }; #better error message
1668
1669   my $custnum = $session->{'custnum'};
1670
1671   my $cust_pay = qsearchs('cust_pay', { 'custnum' => $custnum,
1672                                         'paynum'  => $p->{'paynum'},
1673                                       }
1674                          )
1675     or return { 'error' => "unknown payment ". $p->{'paynum'} };
1676
1677   return { 
1678            'error' => '',
1679            %{ $cust_pay->SSAPI_getinfo },
1680          };
1681 }
1682
1683 sub list_payby {
1684   my $p = shift;
1685
1686   my($context, $session, $custnum) = _custoragent_session_custnum($p);
1687   return { 'error' => $session } if $context eq 'error';
1688
1689   my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1690     or return { 'error' => "unknown custnum $custnum" };
1691
1692   return {
1693     'payby' => [ map {
1694                        my $cust_payby = $_;
1695                        +{
1696                           map { $_ => $cust_payby->$_ }
1697                             qw( custpaybynum weight payby paymask paydate
1698                                 payname paystate paytype
1699                               )
1700                         };
1701                      }
1702                    $cust_main->cust_payby
1703                ],
1704   };
1705 }
1706
1707 sub insert_payby {
1708   my $p = shift;
1709
1710   my($context, $session, $custnum) = _custoragent_session_custnum($p);
1711   return { 'error' => $session } if $context eq 'error';
1712
1713   #XXX payinfo1 + payinfo2 for CHEK?
1714   #or take the opportunity to use separate, more well- named fields?
1715    if ($p->{'payby'} eq 'CHEK') {
1716      $p->{'payinfo1'} =~ /^([\dx]+)$/
1717        or return { 'error' => "illegal account number ". $p->{'payinfo1'} };
1718      my $payinfo1 = $1;
1719       $p->{'payinfo2'} =~ /^([\dx\.]+)$/ # . turned on by echeck-country CA ?
1720        or return { 'error' => "illegal ABA/routing number ". $p->{'payinfo2'} };
1721      my $payinfo2 = $1;
1722      $p->{'payinfo'} = $payinfo1. '@'. $payinfo2;
1723    }
1724    elsif ($p->{'payby'} eq 'CARD') {
1725     $p->{paydate} = $p->{year} . '-' . $p->{month} . '-01' unless $p->{paydate};
1726    }
1727
1728   my $cust_payby = new FS::cust_payby {
1729     'custnum' => $custnum,
1730     map { $_ => $p->{$_} } qw( weight payby payinfo paycvv paydate payname
1731                                paystate paytype payip 
1732                              ),
1733   };
1734
1735   my $error = $cust_payby->insert;
1736   if ( $error ) {
1737     return { 'error' => $error };
1738   } else {
1739     return { 'custpaybynum' => $cust_payby->custpaybynum };
1740   }
1741   
1742 }
1743
1744 sub update_payby {
1745   my $p = shift;
1746
1747   my($context, $session, $custnum) = _custoragent_session_custnum($p);
1748   return { 'error' => $session } if $context eq 'error';
1749
1750   if ($p->{'payby'} eq 'CHEK') {
1751      $p->{'payinfo1'} =~ /^([\dx]+)$/
1752        or return { 'error' => "illegal account number ". $p->{'payinfo1'} };
1753      my $payinfo1 = $1;
1754       $p->{'payinfo2'} =~ /^([\dx\.]+)$/ # . turned on by echeck-country CA ?
1755        or return { 'error' => "illegal ABA/routing number ". $p->{'payinfo2'} };
1756      my $payinfo2 = $1;
1757      $p->{'payinfo'} = $payinfo1. '@'. $payinfo2;
1758   }
1759   elsif ($p->{'payby'} eq 'CARD') {
1760     $p->{paydate} = $p->{year} . '-' . $p->{month} . '-01' unless $p->{paydate};
1761   }
1762
1763   my $cust_payby = qsearchs('cust_payby', {
1764                               'custnum'      => $custnum,
1765                               'custpaybynum' => $p->{'custpaybynum'},
1766                            })
1767     or return { 'error' => 'unknown custpaybynum '. $p->{'custpaybynum'} };
1768
1769   my $cust_main = qsearchs( 'cust_main', {custnum => $cust_payby->custnum} )
1770     or return { 'error' => 'unknown custnum '.$cust_payby->custnum };
1771
1772   foreach my $field (
1773     qw( weight payby payinfo paycvv paydate payname paystate paytype payip )
1774   ) {
1775     next unless exists($p->{$field});
1776     $cust_payby->set($field,$p->{$field});
1777   }
1778   $cust_payby->set( 'paymask' => $cust_payby->mask_payinfo );
1779
1780   # Update column if given a value, and the given value wasn't
1781   # the value generated by $cust_main->masked($column);
1782   $cust_main->set( $_, $p->{$_} )
1783     for grep{ $p->{$_} !~ /^x/i; }
1784         grep{ exists $p->{$_} }
1785         qw/ss stateid/;
1786
1787   # Perform updates within a transaction
1788   local $FS::UID::AutoCommit = 0;
1789
1790   if ( my $error = $cust_payby->replace || $cust_main->replace ) {
1791     dbh->rollback;
1792     return { error => $error };
1793   }
1794
1795   dbh->commit;
1796   return { custpaybynum => $cust_payby->custpaybynum };
1797 }
1798
1799 sub verify_payby {
1800   my $p = shift;
1801
1802   my($context, $session, $custnum) = _custoragent_session_custnum($p);
1803   return { 'error' => $session } if $context eq 'error';
1804
1805   my $cust_payby = qsearchs('cust_payby', {
1806                               'custnum'      => $custnum,
1807                               'custpaybynum' => $p->{'custpaybynum'},
1808                            })
1809     or return { 'error' => 'unknown custpaybynum '. $p->{'custpaybynum'} };
1810
1811   return { 'error' => $cust_payby->verify };
1812   
1813 }
1814
1815 sub delete_payby {
1816   my $p = shift;
1817
1818   my($context, $session, $custnum) = _custoragent_session_custnum($p);
1819   return { 'error' => $session } if $context eq 'error';
1820
1821   my $cust_payby = qsearchs('cust_payby', {
1822                               'custnum'      => $custnum,
1823                               'custpaybynum' => $p->{'custpaybynum'},
1824                            })
1825     or return { 'error' => 'unknown custpaybynum '. $p->{'custpaybynum'} };
1826
1827   my $conf = new FS::Conf;
1828   if (($cust_payby->payby eq "DCHK" || $cust_payby->payby eq "CHEK") && $conf->exists('selfservice-ACH_info_readonly')) {
1829     return { 'error' => "Sorry you do not have permission to delete bank information." };
1830   }
1831   else {
1832     return { 'error' => $cust_payby->delete };
1833   }
1834 }
1835
1836 sub cancel {
1837   my $p = shift;
1838   my $session = _cache->get($p->{'session_id'})
1839     or return { 'error' => "Can't resume session" }; #better error message
1840
1841   my $custnum = $session->{'custnum'};
1842
1843   my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1844     or return { 'error' => "unknown custnum $custnum" };
1845
1846   my @errors = $cust_main->cancel( 'quiet'=>1 );
1847
1848   my $error = scalar(@errors) ? join(' / ', @errors) : '';
1849
1850   return { 'error' => $error };
1851
1852 }
1853
1854 sub pkg_info {
1855   my $p = shift;
1856
1857   my($context, $session, $custnum) = _custoragent_session_custnum($p);
1858   return { 'error' => $session } if $context eq 'error';
1859
1860   my $pkg = qsearchs({
1861     'table'     => 'cust_pkg',
1862     'addl_from' => 'LEFT JOIN part_pkg USING ( pkgpart )',
1863     'hashref'   => {
1864                       'custnum' => $custnum,
1865                       'pkgnum'  => $p->{'pkgnum'},
1866                    },
1867   })
1868     or return {'error' => 'unknown pkg num $pkgnum'};
1869
1870   return {
1871         pkg_label => $pkg->pkg,
1872         pkgpart   => $pkg->pkgpart,
1873         classnum  => $pkg->classnum,
1874   };
1875
1876 }
1877
1878 sub list_pkgs {
1879   my $p = shift;
1880
1881   my($context, $session, $custnum) = _custoragent_session_custnum($p);
1882   return { 'error' => $session } if $context eq 'error';
1883
1884   my $search = { 'custnum' => $custnum };
1885   $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
1886   my $cust_main = qsearchs('cust_main', $search )
1887     or return { 'error' => "unknown custnum $custnum" };
1888
1889   my $conf = new FS::Conf;
1890   my $immutable = $conf->exists('selfservice_immutable-package');
1891   
1892 # the duplication below is necessary:
1893 # 1. to maintain the current buggy behaviour wrt the cust_pkg and part_pkg
1894 # hashes overwriting each other (setup and no_auto fields). Fixing that is a
1895 # non-backwards-compatible change breaking the software of anyone using the API
1896 # instead of the stock selfservice
1897 # 2. to return cancelled packages as well - for wholesale and non-wholesale
1898   if( $conf->exists('selfservice_server-view-wholesale') ) {
1899     return { 'svcnum'   => $session->{'svcnum'},
1900             'custnum'  => $custnum,
1901             'cust_pkg' => [ map {
1902                           { $_->hash,
1903                             immutable => $immutable,
1904                             part_pkg => [ map $_->hashref, $_->part_pkg ],
1905                             part_svc =>
1906                               [ map $_->hashref, $_->available_part_svc ],
1907                             cust_svc => 
1908                               [ map { my $ref = { $_->hash,
1909                                                   label => [ $_->label ],
1910                                                 };
1911                                       $ref->{_password} = $_->svc_x->_password
1912                                         if $context eq 'agent'
1913                                         && $conf->exists('agent-showpasswords')
1914                                         && $_->part_svc->svcdb eq 'svc_acct';
1915                                       $ref;
1916                                     } $_->cust_svc
1917                               ],
1918                           };
1919                         } $cust_main->cust_pkg
1920                   ],
1921     'small_custview' =>
1922       small_custview( $cust_main, $conf->config('countrydefault') ),
1923     'wholesale_view' => 1,
1924     'login_svcpart' => [ $conf->config('selfservice_server-login_svcpart') ],
1925     'date_format' => $conf->config('date_format') || '%m/%d/%Y',
1926     'lnp' => $conf->exists('svc_phone-lnp'),
1927       };
1928   }
1929
1930   { 'svcnum'   => $session->{'svcnum'},
1931     'custnum'  => $custnum,
1932     'cust_pkg' => [ map {
1933                           my $primary_cust_svc = $_->primary_cust_svc;
1934                           +{ $_->hash,
1935                             $_->part_pkg->hash,
1936                             immutable   => $immutable,
1937                             pkg_label   => $_->pkg_locale,
1938                             status      => $_->status,
1939                             statuscolor => $_->statuscolor,
1940                             part_svc =>
1941                               [ map { $_->hashref }
1942                                   grep { $_->selfservice_access ne 'hidden' }
1943                                     $_->available_part_svc
1944                               ],
1945                             cust_svc => 
1946                               [ map { my $ref = { $_->hash,
1947                                                   label => [ $_->label ],
1948                                                 };
1949                                       $ref->{_password} = $_->svc_x->_password
1950                                         if $context eq 'agent'
1951                                         && $conf->exists('agent-showpasswords')
1952                                         && $_->part_svc->svcdb eq 'svc_acct';
1953                                       $ref->{svchash} = { $_->svc_x->hash } if 
1954                                         $_->part_svc->svcdb eq 'svc_phone';
1955                                       $ref->{svchash}->{svcpart} =  $_->part_svc->svcpart
1956                                         if $_->part_svc->svcdb eq 'svc_phone'; # hack
1957                                       $ref;
1958                                     }
1959                                   grep { $_->part_svc->selfservice_access ne 'hidden' }
1960                                     $_->cust_svc
1961                               ],
1962                             primary_cust_svc =>
1963                               $primary_cust_svc
1964                                 ? { $primary_cust_svc->hash,
1965                                     label => [ $primary_cust_svc->label ],
1966                                     finger => $primary_cust_svc->svc_x->finger, #uuh
1967                                     $primary_cust_svc->part_svc->hash,
1968                                   }
1969                                 : {}, #'' ?
1970                           };
1971                         } $cust_main->ncancelled_pkgs
1972                   ],
1973     'small_custview' =>
1974       small_custview( $cust_main, $conf->config('countrydefault') ),
1975     'date_format' => $conf->config('date_format') || '%m/%d/%Y',
1976   };
1977
1978 }
1979
1980 sub list_svcs {
1981   my $p = shift;
1982
1983   my($context, $session, $custnum) = _custoragent_session_custnum($p);
1984   return { 'error' => $session } if $context eq 'error';
1985
1986   my $conf = new FS::Conf;
1987
1988   my $hide_usage = $conf->exists('selfservice_hide-usage') ? 1 : 0;
1989   my $search = { 'custnum' => $custnum };
1990   $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
1991   my $cust_main = qsearchs('cust_main', $search )
1992     or return { 'error' => "unknown custnum $custnum" };
1993
1994   my $pkgnum = $session->{'pkgnum'} || $p->{'pkgnum'} || '';
1995   if ( ! $pkgnum && $p->{'svcnum'} ) {
1996     my $cust_svc = qsearchs('cust_svc', { 'svcnum' => $p->{'svcnum'} } );
1997     $pkgnum = $cust_svc->pkgnum if $cust_svc;
1998   }
1999
2000   my @cust_svc = ();
2001   my @cust_pkg_usage = ();
2002   foreach my $cust_pkg ( $p->{'ncancelled'} 
2003                          ? $cust_main->ncancelled_pkgs
2004                          : $cust_main->unsuspended_pkgs ) {
2005     next if $pkgnum && $cust_pkg->pkgnum != $pkgnum;
2006     push @cust_svc, @{[ $cust_pkg->cust_svc ]}; #@{[ ]} to force array context
2007     push @cust_pkg_usage, $cust_pkg->cust_pkg_usage;
2008   }
2009
2010   @cust_svc = grep { $_->part_svc->selfservice_access ne 'hidden' } @cust_svc;
2011   my %usage_pools;
2012   if (!$hide_usage) {
2013     foreach (@cust_pkg_usage) {
2014       my $part = $_->part_pkg_usage;
2015       my $tag = $part->description . ($part->shared ? 1 : 0);
2016       my $row = $usage_pools{$tag} 
2017             ||= [ $part->description, 0, 0, $part->shared ? 1 : 0 ];
2018       $row->[1] += sprintf('%.1f', $_->minutes); # minutes remaining
2019       $row->[2] += $part->minutes; # minutes total
2020     }
2021   } # otherwise just leave them empty
2022
2023   if ( $p->{'svcdb'} ) {
2024     my $svcdb = ref($p->{'svcdb'}) eq 'HASH'
2025                   ? $p->{'svcdb'}
2026                   : ref($p->{'svcdb'}) eq 'ARRAY'
2027                     ? { map { $_=>1 } @{ $p->{'svcdb'} } }
2028                     : { $p->{'svcdb'} => 1 };
2029     @cust_svc = grep $svcdb->{ $_->part_svc->svcdb }, @cust_svc
2030   }
2031
2032   #@svc_x = sort { $a->domain cmp $b->domain || $a->username cmp $b->username }
2033   #              @svc_x;
2034
2035   my @svcs; # stuff to return to the client
2036   my %bytes_used_total; # for _used columns only
2037   foreach my $cust_svc (@cust_svc) {
2038     my $svc_x = $cust_svc->svc_x;
2039     my($label, $value) = $cust_svc->label;
2040     my $part_svc = $cust_svc->part_svc;
2041     my $svcdb = $part_svc->svcdb;
2042     my $cust_pkg = $cust_svc->cust_pkg;
2043     my $part_pkg = $cust_pkg->part_pkg;
2044
2045     my %hash = (
2046       'svcnum'         => $cust_svc->svcnum,
2047       'display_svcnum' => $cust_svc->display_svcnum,
2048       'svcdb'          => $svcdb,
2049       'label'          => $label,
2050       'value'          => $value,
2051       'pkg_label'      => $cust_pkg->pkg_locale,
2052       'pkg_status'     => $cust_pkg->status,
2053       'readonly'       => ($part_svc->selfservice_access eq 'readonly'),
2054     );
2055
2056     # would it make sense to put this in a svc_* method?
2057
2058     if (!$hide_usage and grep(/^$svcdb$/, qw(svc_acct svc_broadband)) and $part_svc->part_export_usage) {
2059       my $last_bill = $cust_pkg->last_bill || 0;
2060       my $now = time;
2061       my $up_used = $cust_svc->attribute_since_sqlradacct($last_bill,$now,'AcctInputOctets');
2062       my $down_used = $cust_svc->attribute_since_sqlradacct($last_bill,$now,'AcctOutputOctets');
2063       %hash = (
2064         %hash,
2065         'seconds_used'    => $cust_svc->seconds_since_sqlradacct($last_bill,$now),
2066         'upbytes_used'    => display_bytecount($up_used),
2067         'downbytes_used'  => display_bytecount($down_used),
2068         'totalbytes_used' => display_bytecount($up_used + $down_used)
2069       );
2070       $bytes_used_total{'seconds_used'} += $hash{'seconds_used'};
2071       $bytes_used_total{'upbytes_used'} += $up_used;
2072       $bytes_used_total{'downbytes_used'} += $down_used;
2073       $bytes_used_total{'totalbytes_used'} += $up_used + $down_used;
2074     }
2075
2076     if ( $svcdb eq 'svc_acct' ) {
2077       foreach (qw(username email finger seconds)) {
2078         $hash{$_} = $svc_x->$_;
2079       }
2080
2081       if (!$hide_usage) {
2082         %hash = (
2083           %hash,
2084           'upbytes'    => display_bytecount($svc_x->upbytes),
2085           'downbytes'  => display_bytecount($svc_x->downbytes),
2086           'totalbytes' => display_bytecount($svc_x->totalbytes),
2087
2088           'recharge_amount'  => $part_pkg->option('recharge_amount',1),
2089           'recharge_seconds' => $part_pkg->option('recharge_seconds',1),
2090           'recharge_upbytes'    =>
2091             display_bytecount($part_pkg->option('recharge_upbytes',1)),
2092           'recharge_downbytes'  =>
2093             display_bytecount($part_pkg->option('recharge_downbytes',1)),
2094           'recharge_totalbytes' =>
2095             display_bytecount($part_pkg->option('recharge_totalbytes',1)),
2096           # more...
2097         );
2098       }
2099
2100     } elsif ( $svcdb eq 'svc_dsl' ) {
2101
2102       $hash{'phonenum'} = $svc_x->phonenum;
2103       if ( $svc_x->first || $svc_x->get('last') || $svc_x->company ) {
2104         $hash{'name'} = $svc_x->first. ' '. $svc_x->get('last');
2105         $hash{'name'} = $svc_x->company. ' ('. $hash{'name'}. ')'
2106           if $svc_x->company;
2107       } else {
2108         $hash{'name'} = $cust_main->name;
2109       }
2110       # no usage to hide here
2111
2112     } elsif ( $svcdb eq 'svc_phone' or $svcdb eq 'svc_pbx' ) {
2113       if (!$hide_usage) {
2114         # could potentially show lots of things...
2115         $hash{'outbound'} = 1;
2116         $hash{'inbound'}  = 0;
2117         if ( $svcdb eq 'svc_phone' ) {
2118           if ( $part_pkg->plan eq 'voip_inbound' ) {
2119             $hash{'outbound'} = 0;
2120             $hash{'inbound'}  = 1;
2121           } elsif ( $part_pkg->option('selfservice_inbound_format')
2122                 or  $conf->config('selfservice-default_inbound_cdr_format')
2123           ) {
2124             $hash{'inbound'}  = 1;
2125           }
2126         }
2127         foreach (qw(inbound outbound)) {
2128           # hmm...we can't filter by status here, because there might
2129           # not be cdr_terminations at all.  have to go by date.
2130           # find all since the last bill date.
2131           # XXX cdr types?  we are going to need them.
2132           if ( $hash{$_} ) {
2133             my $sum_cdr = $svc_x->sum_cdrs(
2134               'inbound' => ( $_ eq 'inbound' ? 1 : 0 ),
2135               'begin'   => ($cust_pkg->last_bill || 0),
2136               'nonzero' => 1,
2137               'disable_charged_party' => 1,
2138             );
2139             $hash{$_} = $sum_cdr->hashref;
2140           }
2141         }
2142       } # not hiding usage
2143     } # svcdb
2144
2145     push @svcs, \%hash;
2146   } # foreach $cust_svc
2147
2148   foreach my $field (keys %bytes_used_total) {
2149     if ($field =~ /bytes/) {
2150       $bytes_used_total{$field} = display_bytecount($bytes_used_total{$field});
2151     }
2152   }
2153
2154   return { 
2155     'svcnum'   => $session->{'svcnum'},
2156     'custnum'  => $custnum,
2157     'date_format' => $conf->config('date_format') || '%m/%d/%Y',
2158     'view_usage_nodomain' => $conf->exists('selfservice-view_usage_nodomain'),
2159     'svcs'     => \@svcs,
2160     'bytes_used_total' => \%bytes_used_total,
2161     'usage_pools' => [
2162       map { $usage_pools{$_} }
2163       sort { $a cmp $b }
2164       keys %usage_pools
2165     ],
2166     'hide_usage' => $hide_usage,
2167   };
2168
2169 }
2170
2171 sub _customer_svc_x {
2172   my($custnum, $svcnum, $table) = (shift, shift, shift);
2173   my $hashref = ref($svcnum) ? $svcnum : { 'svcnum' => $svcnum };
2174
2175   $custnum =~ /^(\d+)$/ or die "illegal custnum";
2176   my $search = " AND custnum = $1";
2177   #$search .= " AND agentnum = ". $session->{'agentnum'} if $context eq 'agent';
2178
2179   qsearchs( {
2180     'table'     => ($table || 'svc_acct'),
2181     'addl_from' => 'LEFT JOIN cust_svc  USING ( svcnum  ) '.
2182                    'LEFT JOIN cust_pkg  USING ( pkgnum  ) ',#.
2183                    #'LEFT JOIN cust_main USING ( custnum ) ',
2184     'hashref'   => $hashref,
2185     'extra_sql' => $search, #important
2186   } );
2187
2188 }
2189
2190 sub svc_status_html {
2191   my $p = shift;
2192
2193   my($context, $session, $custnum) = _custoragent_session_custnum($p);
2194   return { 'error' => $session } if $context eq 'error';
2195
2196   #XXX only svc_dsl for now
2197   my $svc_x = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_dsl')
2198     or return { 'error' => "Service not found" };
2199
2200   my $html = $svc_x->getstatus_html;
2201
2202   return { 'html' => $html };
2203
2204 }
2205
2206 sub svc_status_hash {
2207   my $p = shift;
2208
2209   my($context, $session, $custnum) = _custoragent_session_custnum($p);
2210   return { 'error' => $session } if $context eq 'error';
2211
2212   #XXX only svc_acct for now
2213   my $svc_x = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_acct')
2214     or return { 'error' => "Service not found" };
2215
2216   my ( $html, $hashref ) = $svc_x->export_getstatus;
2217   return $hashref;
2218
2219 }
2220
2221 sub set_svc_status_hash    { _svc_method_X(shift, 'export_setstatus') }
2222 sub set_svc_status_listadd { _svc_method_X(shift, 'export_setstatus_listadd') }
2223 sub set_svc_status_listdel { _svc_method_X(shift, 'export_setstatus_listdel') }
2224 sub set_svc_status_vacationadd { _svc_method_X(shift, 'export_setstatus_vacationadd') }
2225 sub set_svc_status_vacationdel { _svc_method_X(shift, 'export_setstatus_vacationdel') }
2226
2227 sub _svc_method_X {
2228   my( $p, $method ) = @_;
2229
2230   my($context, $session, $custnum) = _custoragent_session_custnum($p);
2231   return { 'error' => $session } if $context eq 'error';
2232
2233   #XXX only svc_acct for now
2234   my $svc_x = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_acct')
2235     or return { 'error' => "Service not found" };
2236
2237   warn "$method ". join(' / ', map "$_=>".$p->{$_}, keys %$p )
2238     if $DEBUG;
2239   my $error = $svc_x->$method($p); #$p? returns error?
2240   return { 'error' => $error } if $error;
2241
2242   return {}; #? { 'error' => '' }
2243
2244 }
2245
2246 sub acct_forward_info {
2247   my $p = shift;
2248
2249   my($context, $session, $custnum) = _custoragent_session_custnum($p);
2250   return { 'error' => $session } if $context eq 'error';
2251
2252   my $svc_forward = _customer_svc_x( $custnum,
2253                                      { 'srcsvc' => $p->{'svcnum'} },
2254                                      'svc_forward',
2255                                    )
2256     or return { 'error' => '',
2257                 'dst'   => '',
2258               };
2259
2260   return { 'error' => '',
2261            'dst'   => $svc_forward->dst || $svc_forward->dstsvc_acct->email,
2262          };
2263
2264 }
2265
2266 sub process_acct_forward {
2267   my $p = shift;
2268   my($context, $session, $custnum) = _custoragent_session_custnum($p);
2269   return { 'error' => $session } if $context eq 'error';
2270
2271   my $old = _customer_svc_x( $custnum,
2272                              { 'srcsvc' => $p->{'svcnum'} },
2273                              'svc_forward',
2274                            );
2275
2276   if ( $p->{'dst'} eq '' ) {
2277     if ( $old ) {
2278       my $error = $old->delete;
2279       return { 'error' => $error };
2280     }
2281     return { 'error' => '' };
2282   }
2283
2284   my $new = new FS::svc_forward { 'srcsvc' => $p->{'svcnum'},
2285                                   'dst'    => $p->{'dst'},
2286                                 };
2287
2288   my $error;
2289   if ( $old ) {
2290     $new->svcnum($old->svcnum);
2291     my $cust_svc = $old->cust_svc;
2292     $new->svcpart($old->svcpart);
2293     $new->pkgnuym($old->pkgnum);
2294     $error = $new->replace($old);
2295   } else {
2296     my $conf = new FS::Conf;
2297     $new->svcpart($conf->config('selfservice-svc_forward_svcpart'));
2298
2299     my $svc_acct = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_acct' )
2300       or return { 'error' => 'No service' }; #how would we even get here?
2301
2302     $new->pkgnum( $svc_acct->cust_svc->pkgnum );
2303
2304     $error = $new->insert;
2305   }
2306
2307   return { 'error' => $error };
2308
2309 }
2310
2311 sub list_dsl_devices {
2312   my $p = shift;
2313
2314   my($context, $session, $custnum) = _custoragent_session_custnum($p);
2315   return { 'error' => $session } if $context eq 'error';
2316
2317   my $svc_dsl = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_dsl' )
2318     or return { 'error' => "Service not found" };
2319
2320   return {
2321     'devices' => [ map {
2322                          +{ 'mac_addr' => $_->mac_addr };
2323                        } $svc_dsl->dsl_device
2324                  ],
2325   };
2326
2327 }
2328
2329 sub add_dsl_device {
2330   my $p = shift;
2331
2332   my($context, $session, $custnum) = _custoragent_session_custnum($p);
2333   return { 'error' => $session } if $context eq 'error';
2334
2335   my $svc_dsl = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_dsl' )
2336     or return { 'error' => "Service not found" };
2337
2338   return { 'error' => 'No MAC address supplied' }
2339     unless length($p->{'mac_addr'});
2340
2341   my $dsl_device = new FS::dsl_device { 'svcnum'   => $svc_dsl->svcnum,
2342                                         'mac_addr' => scalar($p->{'mac_addr'}),
2343                                       };
2344   my $error = $dsl_device->insert;
2345   return { 'error' => $error };
2346
2347 }
2348
2349 sub delete_dsl_device {
2350   my $p = shift;
2351
2352   my($context, $session, $custnum) = _custoragent_session_custnum($p);
2353   return { 'error' => $session } if $context eq 'error';
2354
2355   my $svc_dsl = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_dsl' )
2356     or return { 'error' => "Service not found" };
2357
2358   my $dsl_device = qsearchs('dsl_device', { 'svcnum'   => $svc_dsl->svcnum,
2359                                             'mac_addr' => scalar($p->{'mac_addr'}),
2360                                           }
2361                            )
2362     or return { 'error' => 'Unknown MAC address: '. $p->{'mac_addr'} };
2363
2364   my $error = $dsl_device->delete;
2365   return { 'error' => $error };
2366
2367 }
2368
2369 sub port_graph {
2370   my $p = shift;
2371   _usage_details( \&_port_graph, $p,
2372                   'svcdb' => 'svc_port',
2373                 );
2374 }
2375
2376 sub _port_graph {
2377   my($svc_port, $begin, $end) = @_;
2378   my @usage = ();
2379   my $pngOrError = $svc_port->graph_png( start=>$begin, end=> $end );
2380   push @usage, { 'png' => $pngOrError };
2381   (@usage);
2382 }
2383
2384 sub _list_svc_usage {
2385   my($svc_acct, $begin, $end) = @_;
2386   my @usage = ();
2387   foreach my $part_export ( 
2388     map { qsearch ( 'part_export', { 'exporttype' => $_ } ) }
2389     qw( sqlradius sqlradius_withdomain )
2390   ) {
2391     push @usage, @ { $part_export->usage_sessions($begin, $end, $svc_acct) };
2392   }
2393   (@usage);
2394 }
2395
2396 sub list_svc_usage {
2397   _usage_details(\&_list_svc_usage, @_);
2398 }
2399
2400 sub _list_support_usage {
2401   my($svc_acct, $begin, $end) = @_;
2402   my @usage = ();
2403   foreach ( grep { $begin <= $_->_date && $_->_date <= $end }
2404             qsearch('acct_rt_transaction', { 'svcnum' => $svc_acct->svcnum })
2405           ) {
2406     push @usage, { 'seconds'  => $_->seconds,
2407                    'support'  => $_->support,
2408                    '_date'    => $_->_date,
2409                    'id'       => $_->transaction_id,
2410                    'creator'  => $_->creator,
2411                    'subject'  => $_->subject,
2412                    'status'   => $_->status,
2413                    'ticketid' => $_->ticketid,
2414                  };
2415   }
2416   (@usage);
2417 }
2418
2419 sub list_support_usage {
2420   _usage_details(\&_list_support_usage, @_);
2421 }
2422
2423 sub _list_cdr_usage {
2424   # XXX CDR type support...
2425   # XXX any way to do a paged search on this?
2426   # we have to return the results all at once...
2427   my($svc_x, $begin, $end, %opt) = @_;
2428   map [ $_->downstream_csv(%opt, 'keeparray' => 1) ],
2429     $svc_x->get_cdrs(
2430       'begin' => $begin,
2431       'end'   => $end,
2432       'disable_charged_party' => 1,
2433       %opt
2434     );
2435 }
2436
2437 sub list_cdr_usage {
2438   my $p = shift;
2439   _usage_details( \&_list_cdr_usage, $p );
2440 }
2441
2442 sub _usage_details {
2443   my($callback, $p, %opt) = @_;
2444   my $conf = FS::Conf->new;
2445
2446   if ( $conf->exists('selfservice_hide-usage') ) {
2447     return { 'error' => 'Viewing usage is not allowed.' };
2448   }
2449
2450   my($context, $session, $custnum) = _custoragent_session_custnum($p);
2451   return { 'error' => $session } if $context eq 'error';
2452
2453   my $search = { 'svcnum' => $p->{'svcnum'} };
2454   $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2455
2456   my $cust_svc = qsearchs( 'cust_svc', $search );
2457   return { 'error' => 'No service selected in list_svc_usage' } 
2458     unless $cust_svc;
2459
2460   my $svc_x = $cust_svc->svc_x;
2461   my $svcdb = $svc_x->table;
2462   my $cust_pkg = $cust_svc->cust_pkg;
2463   my $freq     = $cust_pkg->part_pkg->freq;
2464   my %callback_opt;
2465   my $header = [];
2466   if ( $svcdb eq 'svc_phone' or $svcdb eq 'svc_pbx' ) {
2467     my $format = '';
2468     if ( $p->{inbound} ) {
2469       $format = $cust_pkg->part_pkg->option('selfservice_inbound_format') 
2470                 || $conf->config('selfservice-default_inbound_cdr_format')
2471                 || 'source_default';
2472       $callback_opt{inbound} = 1;
2473     } else {
2474       $format = $cust_pkg->part_pkg->option('selfservice_format')
2475                 || $conf->config('selfservice-default_cdr_format')
2476                 || 'default';
2477     }
2478
2479     $callback_opt{format} = $format;
2480     $callback_opt{use_clid} = 1;
2481     $header = [ split(',', FS::cdr::invoice_header($format) ) ];
2482   }
2483
2484   my $start    = $cust_pkg->setup;
2485   #my $end      = $cust_pkg->bill; # or time?
2486   my $end      = time;
2487
2488   unless ( $p->{beginning} ) {
2489     $p->{beginning} = $cust_pkg->last_bill;
2490     $p->{ending}    = $end;
2491   }
2492
2493   die "illegal beginning" if $p->{beginning} !~ /^\d*$/;
2494   die "illegal ending"    if $p->{ending}    !~ /^\d*$/;
2495
2496   my (@usage) = &$callback($svc_x, $p->{beginning}, $p->{ending}, 
2497     %callback_opt
2498   );
2499
2500   if ( $conf->exists('selfservice-hide_cdr_price') ) {
2501     # ugly kludge, I know
2502     my ($delete_col) = grep { $header->[$_] eq 'Price' } (0..scalar(@$header));
2503     if (defined $delete_col) {
2504       delete($_->[$delete_col]) foreach ($header, @usage);
2505     }
2506   }
2507
2508   #kinda false laziness with FS::cust_main::bill, but perhaps
2509   #we should really change this bit to DateTime and DateTime::Duration
2510   #
2511   #change this bit to use Date::Manip? CAREFUL with timezones (see
2512   # mailing list archive)
2513   my ($nsec,$nmin,$nhour,$nmday,$nmon,$nyear) =
2514     (localtime($p->{ending}) )[0,1,2,3,4,5];
2515   my ($psec,$pmin,$phour,$pmday,$pmon,$pyear) =
2516     (localtime($p->{beginning}) )[0,1,2,3,4,5];
2517
2518   if ( $freq =~ /^\d+$/ ) {
2519     $nmon += $freq;
2520     until ( $nmon < 12 ) { $nmon -= 12; $nyear++; }
2521     $pmon -= $freq;
2522     until ( $pmon >= 0 ) { $pmon += 12; $pyear--; }
2523   } elsif ( $freq =~ /^(\d+)w$/ ) {
2524     my $weeks = $1;
2525     $nmday += $weeks * 7;
2526     $pmday -= $weeks * 7;
2527   } elsif ( $freq =~ /^(\d+)d$/ ) {
2528     my $days = $1;
2529     $nmday += $days;
2530     $pmday -= $days;
2531   } elsif ( $freq =~ /^(\d+)h$/ ) {
2532     my $hours = $1;
2533     $nhour += $hours;
2534     $phour -= $hours;
2535   } else {
2536     return { 'error' => "unparsable frequency: ". $freq };
2537   }
2538   
2539   my $previous  = timelocal_nocheck($psec,$pmin,$phour,$pmday,$pmon,$pyear);
2540   my $next      = timelocal_nocheck($nsec,$nmin,$nhour,$nmday,$nmon,$nyear);
2541
2542   { 
2543     'error'     => '',
2544     'svcnum'    => $p->{svcnum},
2545     'beginning' => $p->{beginning},
2546     'ending'    => $p->{ending},
2547     'inbound'   => $p->{inbound},
2548     'previous'  => ($previous > $start) ? $previous : $start,
2549     'next'      => ($next < $end) ? $next : $end,
2550     'header'    => $header,
2551     'usage'     => \@usage,
2552   };
2553 }
2554
2555 sub order_pkg {
2556   my $p = shift;
2557
2558   my($context, $session, $custnum) = _custoragent_session_custnum($p);
2559   return { 'error' => $session } if $context eq 'error';
2560
2561   my $search = { 'custnum' => $custnum };
2562   $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2563   my $cust_main = qsearchs('cust_main', $search )
2564     or return { 'error' => "unknown custnum $custnum" };
2565
2566   my $status = $cust_main->status;
2567
2568   my %order_pkg_options = ();
2569   if ( $p->{locationnum} > 0 ) {
2570     $order_pkg_options{locationnum} = delete($p->{locationnum});
2571   } elsif ( $p->{address1} ) {
2572     $order_pkg_options{'cust_location'} = new FS::cust_location {
2573       map { $_ => $p->{$_} }
2574         qw( address1 address2 city county state zip country )
2575     };
2576   }
2577
2578   #false laziness w/ClientAPI/Signup.pm
2579
2580   my $cust_pkg = new FS::cust_pkg ( {
2581     'custnum'  => $custnum,
2582     'pkgpart'  => $p->{'pkgpart'},
2583     'quantity' => $p->{'quantity'} || 1,
2584   } );
2585   my $error = $cust_pkg->check;
2586   return { 'error' => $error } if $error;
2587
2588   my @svc = ();
2589   unless ( $p->{'svcpart'} eq 'none' ) {
2590
2591     my $svcdb;
2592     my $svcpart = '';
2593     if ( $p->{'svcpart'} =~ /^(\d+)$/ ) {
2594       $svcpart = $1;
2595       my $part_svc = qsearchs('part_svc', { 'svcpart' => $svcpart } );
2596       return { 'error' => "Unknown svcpart $svcpart" } unless $part_svc;
2597       $svcdb = $part_svc->svcdb;
2598     } else {
2599       $svcdb = 'svc_acct';
2600     }
2601     $svcpart ||= $cust_pkg->part_pkg->svcpart($svcdb);
2602
2603     my %fields = (
2604       'svc_acct'     => [ qw( username domsvc _password sec_phrase popnum ) ],
2605       'svc_domain'   => [ qw( domain ) ],
2606       'svc_phone'    => [ qw( phonenum pin sip_password phone_name ) ],
2607       'svc_external' => [ qw( id title ) ],
2608       'svc_pbx'      => [ qw( id title ) ],
2609     );
2610   
2611     my $svc_x = "FS::$svcdb"->new( {
2612       'svcpart'   => $svcpart,
2613       map { $_ => $p->{$_} } @{$fields{$svcdb}}
2614     } );
2615     
2616     if ( $svcdb eq 'svc_acct' && exists($p->{"snarf_machine1"}) ) {
2617       my @acct_snarf;
2618       my $snarfnum = 1;
2619       while ( length($p->{"snarf_machine$snarfnum"}) ) {
2620         my $acct_snarf = new FS::acct_snarf ( {
2621           'machine'   => $p->{"snarf_machine$snarfnum"},
2622           'protocol'  => $p->{"snarf_protocol$snarfnum"},
2623           'username'  => $p->{"snarf_username$snarfnum"},
2624           '_password' => $p->{"snarf_password$snarfnum"},
2625         } );
2626         $snarfnum++;
2627         push @acct_snarf, $acct_snarf;
2628       }
2629       $svc_x->child_objects( \@acct_snarf );
2630     }
2631     
2632     my $y = $svc_x->setdefault; # arguably should be in new method
2633     return { 'error' => $y } if $y && !ref($y);
2634   
2635     $error = $svc_x->check;
2636     return { 'error' => $error } if $error;
2637
2638     push @svc, $svc_x;
2639
2640   }
2641
2642   $error = $cust_main->order_pkg(
2643     'cust_pkg' => $cust_pkg,
2644     'svcs'     => \@svc,
2645     'noexport' => 1,
2646     %order_pkg_options,
2647   );
2648   return { 'error' => $error } if $error;
2649
2650   my $conf = new FS::Conf;
2651   if ( $conf->exists('signup_server-realtime') ) {
2652
2653     my $bill_error = _do_bop_realtime( $cust_main, $status, 'collect'=>$p->{run_bill_events} );
2654
2655     if ($bill_error) {
2656       $cust_pkg->cancel('quiet'=>1);
2657       return $bill_error;
2658     } else {
2659       $cust_pkg->reexport;
2660     }
2661
2662   } else {
2663     $cust_pkg->reexport;
2664   }
2665
2666   my $svcnum = $svc[0] ? $svc[0]->svcnum : '';
2667
2668   return { error=>'', pkgnum=>$cust_pkg->pkgnum, svcnum=>$svcnum };
2669
2670 }
2671
2672 sub change_pkg {
2673   my $p = shift;
2674
2675   my($context, $session, $custnum) = _custoragent_session_custnum($p);
2676   return { 'error' => $session } if $context eq 'error';
2677
2678   my $conf = new FS::Conf;
2679   my $immutable = $conf->exists('selfservice_immutable-package');
2680   return { 'error' => "Package modification disabled" } if $immutable;
2681
2682   my $search = { 'custnum' => $custnum };
2683   $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2684   my $cust_main = qsearchs('cust_main', $search )
2685     or return { 'error' => "unknown custnum $custnum" };
2686
2687   my $status = $cust_main->status;
2688   my $cust_pkg = qsearchs('cust_pkg', { 'pkgnum' => $p->{pkgnum} } )
2689     or return { 'error' => "unknown package $p->{pkgnum}" };
2690
2691   #if someone does need self-service package change of suspended packages,
2692   # figure out how to be more discriminating
2693   return { error=>"Can't change a suspended package", pkgnum=>$cust_pkg->pkgnum}
2694     if $cust_pkg->status eq 'suspended';
2695
2696   my $err_or_cust_pkg = $cust_pkg->change( 'pkgpart'  => $p->{'pkgpart'},
2697                                            'quantity' => $p->{'quantity'} || 1,
2698                                          );
2699   
2700   my $new_pkg = qsearchs('part_pkg', { 'pkgpart' => $p->{pkgpart} } )
2701     or return { 'error' => "unknown package $p->{pkgpart}" };
2702
2703   return { error=>$err_or_cust_pkg, pkgnum=>$cust_pkg->pkgnum }
2704     unless ref($err_or_cust_pkg);
2705
2706
2707   if ( $conf->exists('signup_server-realtime') ) {
2708
2709     my $bill_error = _do_bop_realtime( $cust_main, $status, 'no_invoice_void'=>1 );
2710
2711     if ($bill_error) {
2712       $err_or_cust_pkg->suspend;
2713       return $bill_error;
2714     } else {
2715       $err_or_cust_pkg->reexport;
2716     }
2717
2718   } else {  
2719     $err_or_cust_pkg->reexport;
2720   }
2721
2722   return { error => '', pkg => $new_pkg->pkg, pkgnum => $err_or_cust_pkg->pkgnum };
2723
2724 }
2725
2726 sub order_recharge {
2727   my $p = shift;
2728
2729   my($context, $session, $custnum) = _custoragent_session_custnum($p);
2730   return { 'error' => $session } if $context eq 'error';
2731
2732   my $search = { 'custnum' => $custnum };
2733   $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2734   my $cust_main = qsearchs('cust_main', $search )
2735     or return { 'error' => "unknown custnum $custnum" };
2736
2737   my $status = $cust_main->status;
2738   my $cust_svc = qsearchs( 'cust_svc', { 'svcnum' => $p->{'svcnum'} } )
2739     or return { 'error' => "unknown service " . $p->{'svcnum'} };
2740
2741   my $svc_x = $cust_svc->svc_x;
2742   my $part_pkg = $cust_svc->cust_pkg->part_pkg;
2743
2744   my %vhash =
2745     map { $_ =~ /^recharge_(.*)$/; $1, $part_pkg->option($_, 1) } 
2746     qw ( recharge_seconds recharge_upbytes recharge_downbytes
2747          recharge_totalbytes );
2748   my $amount = $part_pkg->option('recharge_amount', 1); 
2749   
2750   my ($l, $v, $d) = $cust_svc->label;  # blah
2751   my $pkg = "Recharge $v"; 
2752
2753   my $bill_error = $cust_main->charge($amount, $pkg,
2754      "time: $vhash{seconds}, up: $vhash{upbytes}," . 
2755      "down: $vhash{downbytes}, total: $vhash{totalbytes}",
2756      $part_pkg->taxclass); #meh
2757
2758   my $conf = new FS::Conf;
2759   if ( $conf->exists('signup_server-realtime') && !$bill_error ) {
2760
2761     $bill_error = _do_bop_realtime( $cust_main, $status );
2762
2763     if ($bill_error) {
2764       return $bill_error;
2765     } else {
2766       my $error = $svc_x->recharge (\%vhash);
2767       return { 'error' => $error } if $error;
2768     }
2769
2770   } else {  
2771     my $error = $bill_error;
2772     $error ||= $svc_x->recharge (\%vhash);
2773     return { 'error' => $error } if $error;
2774   }
2775
2776   return { error => '', svc => $cust_svc->part_svc->svc };
2777
2778 }
2779
2780 sub _do_bop_realtime {
2781   my ($cust_main, $status, %opt) = @_;
2782
2783   my $old_balance = $cust_main->balance;
2784
2785   my @cust_bill;
2786   my $bill_error = $cust_main->bill(
2787     'return_bill'   => \@cust_bill,
2788   );
2789
2790   $bill_error ||= $cust_main->apply_payments_and_credits;
2791
2792   $bill_error ||= $cust_main->realtime_collect('selfservice' => 1);
2793
2794   if (    $cust_main->balance > $old_balance
2795        && $cust_main->balance > 0
2796        && ( $cust_main->has_cust_payby_auto || $status eq 'suspended' )
2797      )
2798   {
2799     unless ( $opt{'no_invoice_void'} ) {
2800
2801       #this used to apply a credit, but now we can void invoices...
2802       foreach my $cust_bill (@cust_bill) {
2803         my $voiderror = $cust_bill->void('automatic payment failed');
2804         warn "Error voiding cust bill after decline: $voiderror" if $voiderror;
2805       }
2806
2807     }
2808
2809     return { 'error' => '_decline', 'bill_error' => $bill_error };
2810   }
2811
2812   if ( $opt{'collect'} ) {
2813     my $collect_error = $cust_main->collect();
2814     return { 'error' => '_decline', 'bill_error' => $collect_error }
2815      if $collect_error; #?
2816   }
2817
2818   '';
2819 }
2820
2821 sub renew_info {
2822   my $p = shift;
2823
2824   my($context, $session, $custnum) = _custoragent_session_custnum($p);
2825   return { 'error' => $session } if $context eq 'error';
2826
2827   my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
2828     or return { 'error' => "unknown custnum $custnum" };
2829
2830   my @cust_pkg = sort { $a->bill <=> $b->bill }
2831                  grep { $_->part_pkg->freq ne '0' }
2832                  $cust_main->ncancelled_pkgs;
2833
2834   #return { 'error' => 'No active packages to renew.' } unless @cust_pkg;
2835
2836   my $total = $cust_main->balance;
2837
2838   my @array = map {
2839                     my $bill = $_->bill;
2840                     $total += $_->part_pkg->base_recur($_, \$bill);
2841                     my $renew_date = $_->part_pkg->add_freq($_->bill);
2842                     {
2843                       'pkgnum'             => $_->pkgnum,
2844                       'amount'             => sprintf('%.2f', $total),
2845                       'bill_date'          => $_->bill,
2846                       'bill_date_pretty'   => time2str('%x', $_->bill),
2847                       'renew_date'         => $renew_date,
2848                       'renew_date_pretty'  => time2str('%x', $renew_date),
2849                       'expire_date'        => $_->expire,
2850                       'expire_date_pretty' => time2str('%x', $_->expire),
2851                     };
2852                   }
2853                   @cust_pkg;
2854
2855   return { 'dates' => \@array };
2856
2857 }
2858
2859 sub payment_info_renew_info {
2860   my $p = shift;
2861   my $renew_info   = renew_info($p);
2862   my $payment_info = payment_info($p);
2863   return { %$renew_info,
2864            %$payment_info,
2865          };
2866 }
2867
2868 sub order_renew {
2869   my $p = shift;
2870
2871   my($context, $session, $custnum) = _custoragent_session_custnum($p);
2872   return { 'error' => $session } if $context eq 'error';
2873
2874   my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
2875     or return { 'error' => "unknown custnum $custnum" };
2876
2877   my $date = $p->{'date'};
2878
2879   my $now = time;
2880
2881   #freeside-daily -n -d $date fs_daily $custnum
2882   $cust_main->bill_and_collect( 'time'         => $date,
2883                                 'invoice_time' => $now,
2884                                 'actual_time'  => $now,
2885                                 'check_freq'   => '1d',
2886                               );
2887
2888   return { 'error' => '' };
2889
2890 }
2891
2892 sub suspend_pkg {
2893   my $p = shift;
2894   my $session = _cache->get($p->{'session_id'})
2895     or return { 'error' => "Can't resume session" }; #better error message
2896
2897   my $custnum = $session->{'custnum'};
2898
2899   my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
2900     or return { 'error' => "unknown custnum $custnum" };
2901
2902   my $conf = new FS::Conf;
2903   my $reasonnum = 
2904     $conf->config('selfservice-self_suspend_reason', $cust_main->agentnum)
2905       or return { 'error' => 'Permission denied' };
2906
2907   my $pkgnum = $p->{'pkgnum'};
2908
2909   my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
2910                                         'pkgnum'  => $pkgnum,   } )
2911     or return { 'error' => "unknown pkgnum $pkgnum" };
2912
2913   my $error = $cust_pkg->suspend(reason => $reasonnum);
2914   return { 'error' => $error };
2915
2916 }
2917
2918 sub cancel_pkg {
2919   my $p = shift;
2920   my $session = _cache->get($p->{'session_id'})
2921     or return { 'error' => "Can't resume session" }; #better error message
2922
2923   my $custnum = $session->{'custnum'};
2924   my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
2925     or return { 'error' => "unknown custnum $custnum" };
2926
2927   my $pkgnum = $p->{'pkgnum'};
2928   my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
2929                                         'pkgnum'  => $pkgnum,   } )
2930     or return { 'error' => "unknown pkgnum $pkgnum" };
2931
2932   my $error = $cust_pkg->cancel( 'quiet' => 1,
2933                                  'date'  => $p->{'date'},
2934                                );
2935   return { 'error' => $error };
2936 }
2937
2938 sub provision_phone {
2939   my $p = shift;
2940   my @bulkdid;
2941   @bulkdid = @{$p->{'bulkdid'}} if $p->{'bulkdid'};
2942
2943   #editing an existing phone number
2944   if ( $p->{'svcnum'} && $p->{'svcnum'} =~ /^\d+$/ ) {
2945       my($context, $session, $custnum) = _custoragent_session_custnum($p);
2946       return { 'error' => $session } if $context eq 'error';
2947     
2948       my $svc_phone = qsearchs('svc_phone', { svcnum => $p->{'svcnum'} });
2949       return { 'error' => 'service not found' } unless $svc_phone;
2950       return { 'error' => 'invalid svcnum' } 
2951         if $svc_phone && $svc_phone->cust_svc->cust_pkg->custnum != $custnum;
2952
2953       $svc_phone->email($p->{'email'}) 
2954         if $svc_phone->email ne $p->{'email'} && $p->{'email'} =~ /^([\w\.\d@]+|)$/;
2955       $svc_phone->forwarddst($p->{'forwarddst'}) 
2956         if $svc_phone->forwarddst ne $p->{'forwarddst'} 
2957             && $p->{'forwarddst'} =~ /^(\d+|)$/;
2958       return { 'error' => $svc_phone->replace };
2959  }
2960
2961   # single DID LNP
2962   unless ( $p->{'lnp'} ) {
2963     $p->{'lnp_desired_due_date'} = parse_datetime($p->{'lnp_desired_due_date'});
2964     $p->{'lnp_status'} = "portingin";
2965     return _provision( 'FS::svc_phone',
2966                   [qw(lnp_desired_due_date lnp_other_provider 
2967                     lnp_other_provider_account phonenum countrycode lnp_status)],
2968                   [qw(phonenum countrycode)],
2969                   $p,
2970                   @_
2971                 );
2972   }
2973
2974   # single DID order (the usual case)
2975   unless (scalar(@bulkdid)) {
2976     return _provision( 'FS::svc_phone',
2977                   [qw(phonenum countrycode)],
2978                   [qw(phonenum countrycode)],
2979                   $p,
2980                   @_
2981                 );
2982   }
2983
2984   # bulk DID order case
2985   my $error;
2986   foreach my $did ( @bulkdid ) {
2987     $did =~ s/[^0-9]//g;
2988     $error = _provision( 'FS::svc_phone',
2989               [qw(phonenum countrycode)],
2990               [qw(phonenum countrycode)],
2991               {
2992                 'pkgnum' => $p->{'pkgnum'},
2993                 'svcpart' => $p->{'svcpart'},
2994                 'phonenum' => $did,
2995                 'countrycode' => $p->{'countrycode'},
2996                 'session_id' => $p->{'session_id'},
2997               }
2998             );
2999     return $error if ($error->{'error'} && length($error->{'error'}) > 1);
3000   }
3001   { 'bulkdid' => [ @bulkdid ], 'svc' => $error->{'svc'} }
3002 }
3003
3004 sub provision_pbx {
3005   my $p = shift;
3006   warn "provision_pbx called\n"
3007     if $DEBUG;
3008
3009   warn "provision_pbx calling _provision\n"
3010     if $DEBUG;
3011   _provision( 'FS::svc_pbx',
3012               [qw(id title max_extensions max_simultaneous ip_addr)],
3013               [qw(id title max_extensions max_simultaneous ip_addr)],
3014               $p,
3015               @_
3016             );
3017 }
3018
3019 sub provision_acct {
3020   my $p = shift;
3021   warn "provision_acct called\n"
3022     if $DEBUG;
3023
3024   return { 'error' => gettext('passwords_dont_match') }
3025     if $p->{'_password'} ne $p->{'_password2'};
3026   return { 'error' => gettext('empty_password') }
3027     unless length($p->{'_password'});
3028  
3029   if ($p->{'domsvc'}) {
3030     my %domains = domain_select_hash FS::svc_acct(map { $_ => $p->{$_} }
3031                                                   qw ( svcpart pkgnum ) );
3032     return { 'error' => gettext('invalid_domain') }
3033       unless ($domains{$p->{'domsvc'}});
3034   }
3035
3036   warn "provision_acct calling _provision\n"
3037     if $DEBUG;
3038   _provision( 'FS::svc_acct',
3039               [qw(username _password domsvc)],
3040               [qw(username _password domsvc)],
3041               $p,
3042               @_
3043             );
3044 }
3045
3046 sub provision_external {
3047   my $p = shift;
3048   #_provision( 'FS::svc_external', [qw(id title)], [qw(id title)], $p, @_ );
3049   _provision( 'FS::svc_external',
3050               [],
3051               [qw(id title)],
3052               $p,
3053               @_
3054             );
3055 }
3056
3057 sub provision_forward {
3058   my $p = shift;
3059   _provision( 'FS::svc_forward',
3060               ['srcsvc','src','dstsvc','dst'],
3061               [],
3062               $p,
3063             );
3064 }
3065
3066 sub _provision {
3067   my( $class, $fields, $return_fields, $p ) = splice(@_, 0, 4);
3068   warn "_provision called for $class\n"
3069     if $DEBUG;
3070
3071   my($context, $session, $custnum) = _custoragent_session_custnum($p);
3072   return { 'error' => $session } if $context eq 'error';
3073
3074   my $search = { 'custnum' => $custnum };
3075   $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
3076   my $cust_main = qsearchs('cust_main', $search )
3077     or return { 'error' => "unknown custnum $custnum" };
3078
3079   my $pkgnum = $p->{'pkgnum'};
3080
3081   warn "searching for custnum $custnum pkgnum $pkgnum\n"
3082     if $DEBUG;
3083   my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
3084                                         'pkgnum'  => $pkgnum,
3085                                                                } )
3086     or return { 'error' => "unknown pkgnum $pkgnum" };
3087
3088   warn "searching for svcpart ". $p->{'svcpart'}. "\n"
3089     if $DEBUG;
3090   my $part_svc = qsearchs('part_svc', { 'svcpart' => $p->{'svcpart'} } )
3091     or return { 'error' => "unknown svcpart $p->{'svcpart'}" };
3092
3093   return { error=> 'svcpart '. $p->{'svcpart'}. " is not a $class definition" }
3094     if $class ne 'FS::'. $part_svc->svcdb;
3095
3096   warn "creating $class record\n"
3097     if $DEBUG;
3098   my $svc_x = $class->new( {
3099     'pkgnum'  => $p->{'pkgnum'},
3100     'svcpart' => $p->{'svcpart'},
3101     map { $_ => $p->{$_} } @$fields
3102   } );
3103
3104   my %insert_args = ();
3105   #i shouldn't be a special case here (pass an option or something)
3106   if ( $class eq 'FS::svc_phone'
3107          && grep length($p->{$_}), @location_editable_fields
3108      )
3109   {
3110     $insert_args{'cust_location'} = new FS::cust_location {
3111       map { $_ => $p->{$_} } @location_editable_fields
3112     };
3113   }
3114
3115   warn "inserting $class record\n"
3116     if $DEBUG;
3117   my $error = $svc_x->insert(%insert_args);
3118
3119   unless ( $error ) {
3120     warn "finding inserted record for svcnum ". $svc_x->svcnum. "\n"
3121       if $DEBUG;
3122     $svc_x = qsearchs($svc_x->table, { 'svcnum' => $svc_x->svcnum })
3123   }
3124
3125   my $return = { 'svc'   => $part_svc->svc,
3126                  'error' => $error,
3127                  map { $_ => $svc_x->get($_) } @$return_fields
3128                };
3129   warn "_provision returning ". Dumper($return). "\n"
3130     if $DEBUG;
3131   return $return;
3132
3133 }
3134
3135 sub part_svc_info {
3136   my $p = shift;
3137
3138   my($context, $session, $custnum) = _custoragent_session_custnum($p);
3139   return { 'error' => $session } if $context eq 'error';
3140
3141   my $search = { 'custnum' => $custnum };
3142   $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
3143   my $cust_main = qsearchs('cust_main', $search )
3144     or return { 'error' => "unknown custnum $custnum" };
3145
3146   my $pkgnum = $p->{'pkgnum'};
3147
3148   my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
3149                                         'pkgnum'  => $pkgnum,
3150                                                                } )
3151     or return { 'error' => "unknown pkgnum $pkgnum" };
3152
3153   my $svcpart = $p->{'svcpart'};
3154
3155   my $pkg_svc = qsearchs('pkg_svc', { 'pkgpart' => $cust_pkg->pkgpart,
3156                                       'svcpart' => $svcpart,           } )
3157     or return { 'error' => "unknown svcpart $svcpart for pkgnum $pkgnum" };
3158   my $part_svc = $pkg_svc->part_svc;
3159
3160   my $conf = new FS::Conf;
3161
3162   my $ret = {
3163     'svc'     => $part_svc->svc,
3164     'svcdb'   => $part_svc->svcdb,
3165     'pkgnum'  => $pkgnum,
3166     'svcpart' => $svcpart,
3167     'custnum' => $custnum,
3168
3169     'security_phrase' => 0, #XXX !
3170     'svc_acct_pop'    => [], #XXX !
3171     'popnum'          => '',
3172     'init_popstate'   => '',
3173     'popac'           => '',
3174     'acstate'         => '',
3175
3176     'small_custview' =>
3177       small_custview( $cust_main, $conf->config('countrydefault') ),
3178
3179   };
3180
3181   if ($p->{'svcnum'} && $p->{'svcnum'} =~ /^\d+$/ 
3182                      && $ret->{'svcdb'} eq 'svc_phone') {
3183         $ret->{'svcnum'} = $p->{'svcnum'};
3184         my $svc_phone = qsearchs('svc_phone', { svcnum => $p->{'svcnum'} });
3185         if ( $svc_phone && $svc_phone->cust_svc->cust_pkg->custnum == $custnum ) {
3186             $ret->{'email'} = $svc_phone->email;
3187             $ret->{'forwarddst'} = $svc_phone->forwarddst;
3188         }
3189   }
3190
3191   if ($ret->{'svcdb'} eq 'svc_forward') {
3192     $ret->{'forward_emails'} = {$cust_pkg->forward_emails()};
3193   }
3194
3195   $ret;
3196 }
3197
3198 sub unprovision_svc {
3199   my $p = shift;
3200
3201   my($context, $session, $custnum) = _custoragent_session_custnum($p);
3202   return { 'error' => $session } if $context eq 'error';
3203
3204   my $search = { 'custnum' => $custnum };
3205   $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
3206   my $cust_main = qsearchs('cust_main', $search )
3207     or return { 'error' => "unknown custnum $custnum" };
3208
3209   my $svcnum = $p->{'svcnum'};
3210
3211   my $cust_svc = qsearchs('cust_svc', { 'svcnum'  => $svcnum, } )
3212     or return { 'error' => "unknown svcnum $svcnum" };
3213
3214   return { 'error' => "Service $svcnum does not belong to customer $custnum" }
3215     unless $cust_svc->cust_pkg->custnum == $custnum;
3216
3217   my $conf = new FS::Conf;
3218
3219   return { 'svc'   => $cust_svc->part_svc->svc,
3220            'error' => $cust_svc->cancel,
3221            'small_custview' =>
3222              small_custview( $cust_main, $conf->config('countrydefault') ),
3223          };
3224
3225 }
3226
3227 sub myaccount_passwd {
3228   my $p = shift;
3229   my($context, $session, $custnum) = _custoragent_session_custnum($p);
3230   return { 'error' => $session } if $context eq 'error';
3231
3232   return { 'error' => "New passwords don't match." }
3233     if $p->{'new_password'} ne $p->{'new_password2'};
3234
3235   return { 'error' => 'Enter new password' }
3236     unless length($p->{'new_password'});
3237
3238   #my $search = { 'custnum' => $custnum };
3239   #$search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
3240   $custnum =~ /^(\d+)$/ or die "illegal custnum";
3241   my $search = " AND custnum = $1";
3242   $search .= " AND agentnum = ". $session->{'agentnum'} if $context eq 'agent';
3243
3244   my $svc_acct = qsearchs( {
3245     'table'     => 'svc_acct',
3246     'addl_from' => 'LEFT JOIN cust_svc  USING ( svcnum  ) '.
3247                    'LEFT JOIN cust_pkg  USING ( pkgnum  ) '.
3248                    'LEFT JOIN cust_main USING ( custnum ) ',
3249     'hashref'   => { 'svcnum' => $p->{'svcnum'}, },
3250     'extra_sql' => $search, #important
3251   } )
3252     or return { 'error' => "Service not found" };
3253
3254   my $error = '';
3255
3256   my $conf = new FS::Conf;
3257
3258   return { 'error' => 'Incorrect current password.' }
3259     if  ( exists($p->{'old_password'})
3260           || $conf->exists('selfservice-password_change_oldpass')
3261         )
3262     && ! $svc_acct->check_password($p->{'old_password'});
3263
3264   $error ||= $svc_acct->is_password_allowed($p->{'new_password'})
3265          ||  $svc_acct->set_password($p->{'new_password'})
3266          ||  $svc_acct->replace();
3267
3268   #regular pw change in self-service should change contact pw too, otherwise its
3269   #way too confusing.  hell its confusing they're separate at all, but alas.
3270   #need to support the "ISP provides email that's used as a contact email" case
3271   #as well as we can.
3272   my $contact = FS::contact->by_selfservice_email($svc_acct->email);
3273   if ( $contact && qsearchs('cust_contact', { contactnum=> $contact->contactnum,
3274                                               custnum   => $custnum,
3275                                               selfservice_access => 'Y',
3276                                             }
3277                            )
3278   ) {
3279     #svc_acct was successful but this one returns an error?  "shouldn't happen"
3280     #don't recheck is_password_allowed here; if the svc_acct password was
3281     #legal, that's good enough
3282     $error ||= $contact->change_password($p->{'new_password'});
3283   }
3284
3285   my($label, $value) = $svc_acct->cust_svc->label;
3286
3287   return { 'error' => $error,
3288            'label' => $label,
3289            'value' => $value,
3290          };
3291
3292 }
3293
3294 sub reset_passwd {
3295   my $p = shift;
3296
3297   my $info = skin_info($p);
3298
3299   my $conf = new FS::Conf;
3300   my $verification = $conf->config('selfservice-password_reset_verification')
3301     or return { %$info, 'error' => 'Password resets disabled' };
3302
3303   my $contact = '';
3304   my $svc_acct = '';
3305   my $cust_main = '';
3306   if ( $p->{'email'} ) { #new-style, changes contact and svc_acct
3307   
3308     $contact = FS::contact->by_selfservice_email($p->{'email'}, 'case_insensitive');
3309
3310     my @customers = grep $_->selfservice_access, $contact->cust_contact;
3311     my @cust_contact;
3312
3313     foreach my $customer (@customers) {
3314       if ($conf->exists('username-uppercase') || $conf->exists('username-uppercase', $customer->cust_main->agentnum)) {
3315         my $check_contact = FS::contact->by_selfservice_email_custnum($p->{email}, $customer->custnum);
3316         push @cust_contact, $customer if $check_contact;
3317       }
3318       else { push @cust_contact, $customer; }
3319     }
3320
3321     $contact = '' unless @cust_contact;
3322     $cust_main = $cust_contact[0]->cust_main if scalar(@cust_contact) == 1;
3323
3324     #also look for an svc_acct, otherwise it would be super confusing
3325
3326     my($username, $domain) = split('@', $p->{'email'});
3327     my $svc_domain = qsearchs('svc_domain', { 'domain' => $domain } );
3328     if ( $svc_domain ) {
3329       $svc_acct = qsearchs('svc_acct', { 'username' => $username,
3330                                          'domsvc'   => $svc_domain->svcnum  }
3331                           );
3332       if ( $svc_acct ) {
3333         my $cust_pkg = $svc_acct->cust_svc->cust_pkg;
3334         $cust_main ||= $cust_pkg->cust_main if $cust_pkg;
3335
3336         #precaution: don't change svc_acct password not part of the same
3337         # customer as contact
3338         $svc_acct = '' if ! $cust_pkg
3339                        || $cust_pkg->custnum != $cust_main->custnum;
3340       }
3341       
3342     }
3343
3344     return { %$info, 'error' => 'Email address not found' }
3345       unless $contact || $svc_acct;
3346
3347   } elsif ( $p->{'username'} ) { #old style, looks in svc_acct only
3348
3349     my $svc_domain = qsearchs('svc_domain', { 'domain' => $p->{'domain'} } )
3350       or return { %$info, 'error' => 'Account not found' };
3351
3352     $svc_acct = qsearchs('svc_acct', { 'username' => $p->{'username'},
3353                                        'domsvc'   => $svc_domain->svcnum  }
3354                         )
3355       or return { %$info, 'error' => 'Account not found' };
3356
3357     my $cust_pkg = $svc_acct->cust_svc->cust_pkg
3358       or return { %$info, 'error' => 'Account not found' };
3359
3360     $cust_main = $cust_pkg->cust_main;
3361
3362   }
3363
3364   return { %$info, 'error' => 'Multi-customer contacts incompatible with customer-based verification' }
3365     if ! $cust_main && $verification ne 'email';
3366
3367   my %verify = (
3368     'email'   => sub { 1; },
3369     'paymask' => sub { 
3370       my( $p, $cust_main ) = @_;
3371       $cust_main->payby =~ /^(CARD|DCRD|CHEK|DCHK)$/
3372         && $p->{'paymask'} eq substr($cust_main->paymask, -4)
3373     },
3374     'amount'  => sub {
3375       my( $p, $cust_main ) = @_;
3376       my $cust_pay = qsearchs({
3377         'table' => 'cust_pay',
3378         'hashref' => { 'custnum' => $cust_main->custnum },
3379         'order_by' => 'ORDER BY _date DESC LIMIT 1',
3380       })
3381         or return 0;
3382
3383       $p->{'amount'} == $cust_pay->paid;
3384     },
3385     'zip'     => sub {
3386       my( $p, $cust_main ) = @_;
3387       $p->{'zip'} eq $cust_main->zip
3388         || ( $cust_main->ship_zip && $p->{'zip'} eq $cust_main->ship_zip );
3389     },
3390   );
3391
3392   foreach my $verify ( split(',', $verification) ) {
3393
3394     &{ $verify{$verify} }( $p, $cust_main )
3395       or return { %$info, 'error' => 'Account not found' };
3396
3397   }
3398
3399   #okay, we're verified
3400
3401   if ( $contact ) {
3402
3403     my $error = $contact->send_reset_email(
3404                             'svcnum' => ($svc_acct ? $svc_acct->svcnum : ''),
3405                           );
3406
3407     if ( $error ) {
3408       return { %$info, 'error' => $error }; #????
3409     }
3410
3411   } elsif ( $svc_acct ) {
3412
3413     #create a unique session
3414
3415     my $reset_session = {
3416       'svcnum'   => $svc_acct->svcnum,
3417       'agentnum' => $svc_acct->cust_main->agentnum,
3418     };
3419
3420     my $timeout = '1 hour'; #?
3421
3422     my $reset_session_id;
3423     do {
3424       $reset_session_id = sha512_hex(time(). {}. rand(). $$)
3425     } until ( ! defined _cache->get("reset_passwd_$reset_session_id") );
3426       #just in case
3427
3428     _cache->set( "reset_passwd_$reset_session_id", $reset_session, $timeout );
3429
3430     #email it
3431
3432     my $msgnum = $conf->config('selfservice-password_reset_msgnum',
3433                                $cust_main->agentnum);
3434     #die "selfservice-password_reset_msgnum unset" unless $msgnum;
3435     return { %$info, 'error' => "selfservice-password_reset_msgnum unset" }
3436       unless $msgnum;
3437     my $msg_template = qsearchs('msg_template', { msgnum => $msgnum } );
3438     my $error = $msg_template->send( 'cust_main'     => $cust_main,
3439                                      'object'        => $svc_acct,
3440                                      'substitutions' => {
3441                                        'session_id' => $reset_session_id,
3442                                      }
3443                                    );
3444     if ( $error ) {
3445       return { %$info, 'error' => $error }; #????
3446     }
3447
3448   }
3449
3450   return { %$info, 'error' => '' };
3451 }
3452
3453 sub check_reset_passwd {
3454   my $p = shift;
3455
3456   my $conf = new FS::Conf;
3457   my $verification = $conf->config('selfservice-password_reset_verification')
3458     or return { 'error' => 'Password resets disabled' };
3459
3460   my $reset_session = _cache->get('reset_passwd_'. $p->{'session_id'})
3461     or return { 'error' => "Can't resume session" }; #better error message
3462
3463   if ( $reset_session->{'svcnum'} ) {
3464
3465     my $svcnum = $reset_session->{'svcnum'};
3466
3467     my $svc_acct = qsearchs('svc_acct', { 'svcnum' => $svcnum } )
3468       or return { 'error' => "Service not found" };
3469
3470     $p->{'agentnum'} = $svc_acct->cust_svc->cust_pkg->cust_main->agentnum;
3471     my $info = skin_info($p);
3472
3473     return { %$info,
3474              'error'      => '',
3475              'session_id' => $p->{'session_id'},
3476              'username'   => $svc_acct->username,
3477            };
3478
3479   } elsif ( $reset_session->{'contactnum'} ) {
3480
3481     my $contactnum = $reset_session->{'contactnum'};
3482
3483     my $contact = qsearchs('contact', { 'contactnum' => $contactnum } )
3484       or return { 'error' => "Contact not found" };
3485
3486     my @contact_email = $contact->contact_email;
3487     return { 'error' => 'No contact email' } unless @contact_email;
3488
3489     my @cust_contact = grep $_->selfservice_access, $contact->cust_contact;
3490     $p->{'agentnum'} = $cust_contact[0]->cust_main->agentnum
3491       if scalar(@cust_contact) == 1;
3492     my $info = skin_info($p);
3493
3494     return { %$info,
3495              'error'      => '',
3496              'session_id' => $p->{'session_id'},
3497              'email'      => $contact_email[0]->email, #the first?
3498            };
3499
3500   } else {
3501
3502     return { 'error' => 'No svcnum or contactnum in session' }; #??
3503
3504   }
3505
3506 }
3507
3508 sub process_reset_passwd {
3509   my $p = shift;
3510
3511   my $conf = new FS::Conf;
3512   my $verification = $conf->config('selfservice-password_reset_verification')
3513     or return { 'error' => 'Password resets disabled' };
3514
3515   my $reset_session = _cache->get('reset_passwd_'. $p->{'session_id'})
3516     or return { 'error' => "Can't resume session" }; #better error message
3517
3518   my $info = '';
3519
3520   my $svc_acct = '';
3521   if ( $reset_session->{'svcnum'} ) {
3522
3523     my $svcnum = $reset_session->{'svcnum'};
3524
3525     $svc_acct = qsearchs('svc_acct', { 'svcnum' => $svcnum } )
3526       or return { 'error' => "Service not found" };
3527
3528     $p->{'agentnum'} ||= $svc_acct->cust_svc->cust_pkg->cust_main->agentnum;
3529     $info ||= skin_info($p);
3530
3531   }
3532
3533   my $contact = '';
3534   if ( $reset_session->{'contactnum'} ) {
3535
3536     my $contactnum = $reset_session->{'contactnum'};
3537
3538     $contact = qsearchs('contact', { 'contactnum' => $contactnum } )
3539       or return { 'error' => "Contact not found" };
3540
3541     my @cust_contact = grep $_->selfservice_access, $contact->cust_contact;
3542     $p->{'agentnum'} = $cust_contact[0]->cust_main->agentnum
3543       if scalar(@cust_contact) == 1;
3544     $info ||= skin_info($p);
3545
3546   }
3547
3548   return { %$info, 'error' => "New passwords don't match." }
3549     if $p->{'new_password'} ne $p->{'new_password2'};
3550
3551   return { %$info, 'error' => 'Enter new password' }
3552     unless length($p->{'new_password'});
3553
3554   if ( $svc_acct ) {
3555
3556     my $error ||= $svc_acct->is_password_allowed($p->{'new_password'})
3557               ||  $svc_acct->set_password($p->{'new_password'})
3558               ||  $svc_acct->replace();
3559
3560     return { %$info, 'error' => $error } if $error;
3561
3562     #my($label, $value) = $svc_acct->cust_svc->label;
3563     #return { 'error' => $error,
3564     #         #'label' => $label,
3565     #         #'value' => $value,
3566     #       };
3567
3568   }
3569
3570   if ( $contact ) {
3571
3572     my $error = $contact->is_password_allowed($p->{'new_password'})
3573             ||  $contact->change_password($p->{'new_password'});
3574
3575     return { %$info, 'error' => $error }; # if $error;
3576
3577   }
3578
3579   #password changed ,so remove session, don't want it reused
3580   _cache->remove($p->{'session_id'});
3581
3582   return { %$info, 'error' => '' };
3583
3584 }
3585
3586 sub validate_passwd {
3587   my $p = shift;
3588
3589   my %result;
3590   %result = ( 'fieldid' => $p->{'fieldid'} )
3591     if $p->{'fieldid'} =~ /^\w+$/;
3592
3593   return { %result, 'password_invalid' => 'Enter new password' }
3594     unless length($p->{'check_password'});
3595
3596   my $svc_acct;
3597   if ($p->{'svcnum'}) {
3598     # false laziness with myaccount_passwd
3599     my($context, $session, $custnum) = _custoragent_session_custnum($p);
3600     return { %result, 'error' => $session } if $context eq 'error';
3601
3602     $custnum =~ /^(\d+)$/ or die "illegal custnum";
3603     my $search = " AND custnum = $1";
3604     $search .= " AND agentnum = ". $session->{'agentnum'} if $context eq 'agent';
3605
3606     $svc_acct = qsearchs( {
3607       'table'     => 'svc_acct',
3608       'addl_from' => 'LEFT JOIN cust_svc  USING ( svcnum  ) '.
3609                      'LEFT JOIN cust_pkg  USING ( pkgnum  ) '.
3610                      'LEFT JOIN cust_main USING ( custnum ) ',
3611       'hashref'   => { 'svcnum' => $p->{'svcnum'}, },
3612       'extra_sql' => $search, #important
3613     } )
3614       or return { %result, 'error' => "Service not found" };
3615     # end false laziness
3616   }
3617
3618   $svc_acct ||= new FS::svc_acct {};
3619
3620   my $error = $svc_acct->is_password_allowed($p->{'check_password'});
3621   return { %result, 'password_invalid' => $error } if $error;
3622   return { %result, 'password_valid' => 1 };
3623 }
3624
3625 sub list_tickets {
3626   my $p = shift;
3627   my($context, $session, $custnum) = _custoragent_session_custnum($p);
3628   return { 'error' => $session } if $context eq 'error';
3629
3630   my @tickets = ();
3631   if ( $session->{'pkgnum'} ) { 
3632
3633     #tickets for specific service with pkg-balances on
3634     my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
3635                                           'pkgnum'  => $session->{'pkgnum'} })
3636                      or return { 'error' => 'unknown package' };
3637     foreach my $cust_svc ( $cust_pkg->cust_svc ) {
3638       push @tickets, $cust_svc->tickets( $p->{status} );
3639     }
3640
3641   } else {
3642
3643     my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
3644       or return { 'error' => "unknown custnum $custnum" };
3645
3646     @tickets = $cust_main->tickets( $p->{status} );
3647   }
3648
3649   # unavoidable false laziness w/ httemplate/view/cust_main/tickets.html
3650   if ( $FS::TicketSystem::system && FS::TicketSystem->selfservice_priority ) {
3651
3652     @tickets = grep { $_->{'_selfservice_priority'}
3653                         !~ /^\s*(closed?|resolved?|done)\s*/i }
3654                  @tickets;
3655
3656     my $conf = new FS::Conf;
3657     my $dir = $conf->exists('ticket_system-priority_reverse') ? -1 : 1;
3658     +{ tickets => [ 
3659          sort { 
3660            (
3661              ($a->{'_selfservice_priority'} eq '') <=>
3662              ($b->{'_selfservice_priority'} eq '')
3663            ) ||
3664            ( $dir * 
3665              ($b->{'_selfservice_priority'} <=> $a->{'_selfservice_priority'})
3666            )
3667          } @tickets
3668        ]
3669     };
3670   } else {
3671     +{ tickets => \@tickets };
3672   }
3673
3674 }
3675
3676 sub create_ticket {
3677   my $p = shift;
3678   my($context, $session, $custnum) = _custoragent_session_custnum($p);
3679   return { 'error' => $session } if $context eq 'error';
3680
3681   warn "$me create_ticket: initializing ticket system\n" if $DEBUG;
3682   FS::TicketSystem->init();
3683
3684   my $conf = new FS::Conf;
3685   my $queue = $p->{'queue'}
3686               || $conf->config('ticket_system-selfservice_queueid')
3687               || $conf->config('ticket_system-default_queueid');
3688
3689   warn "$me create_ticket: creating ticket\n" if $DEBUG;
3690   my $err_or_ticket = FS::TicketSystem->create_ticket(
3691     '', #create RT session based on FS CurrentUser (fs_selfservice)
3692     'queue'   => $queue,
3693     'custnum' => $custnum,
3694     'svcnum'  => $session->{'svcnum'},
3695     map { $_ => $p->{$_} } qw( requestor cc subject message mime_type )
3696   );
3697
3698   if ( ref($err_or_ticket) ) {
3699     warn "$me create_ticket: successful: ". $err_or_ticket->id. "\n"
3700       if $DEBUG;
3701     return { 'error'     => '',
3702              'ticket_id' => $err_or_ticket->id,
3703            };
3704   } else {
3705     warn "$me create_ticket: unsuccessful: $err_or_ticket\n"
3706       if $DEBUG;
3707     return { 'error' => $err_or_ticket };
3708   }
3709
3710
3711 }
3712
3713 sub did_report {
3714   my $p = shift;
3715   my($context, $session, $custnum) = _custoragent_session_custnum($p);
3716   return { 'error' => $session } if $context eq 'error';
3717  
3718   return { error => 'requested format not implemented' } 
3719     unless ($p->{'format'} eq 'csv' || $p->{'format'} eq 'xls');
3720
3721   my $conf = new FS::Conf;
3722   my $age_threshold = 0;
3723   $age_threshold = time() - $conf->config('selfservice-recent-did-age')
3724     if ($p->{'recentonly'} && $conf->exists('selfservice-recent-did-age'));
3725
3726   my $search = { 'custnum' => $custnum };
3727   $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
3728   my $cust_main = qsearchs('cust_main', $search )
3729     or return { 'error' => "unknown custnum $custnum" };
3730
3731 # does it make more sense to just run one sql query for this instead of all the
3732 # insanity below? would increase performance greately for large data sets?
3733   my @svc_phone = ();
3734   foreach my $cust_pkg ( $cust_main->ncancelled_pkgs ) {
3735         my @part_svc = $cust_pkg->part_svc;
3736         foreach my $part_svc ( @part_svc ) {
3737             if($part_svc->svcdb eq 'svc_phone'){
3738                 my @cust_pkg_svc = @{$part_svc->cust_pkg_svc};
3739                 foreach my $cust_pkg_svc ( @cust_pkg_svc ) {
3740                     push @svc_phone, $cust_pkg_svc->svc_x
3741                         if $cust_pkg_svc->date_inserted >= $age_threshold;
3742                 }
3743             }
3744         }
3745   }
3746
3747   my $csv;
3748   my $xls;
3749   my($xls_r,$xls_c) = (0,0);
3750   my $xls_workbook;
3751   my $content = '';
3752   my @fields = qw( countrycode phonenum pin sip_password phone_name );
3753   if($p->{'format'} eq 'csv') {
3754     $csv = new Text::CSV_XS { 'always_quote' => 1,
3755                                  'eol'          => "\n",
3756                                 };
3757     return { 'error' => 'Unable to create CSV' } unless $csv->combine(@fields);
3758     $content .= $csv->string;
3759   }
3760   elsif($p->{'format'} eq 'xls') {
3761     my $XLS1 = new IO::Scalar \$content;
3762     $xls_workbook = Spreadsheet::WriteExcel->new($XLS1) 
3763         or return { 'error' => "Error opening .xls file: $!" };
3764     $xls = $xls_workbook->add_worksheet('DIDs');
3765     foreach ( @fields ) {
3766         $xls->write(0,$xls_c++,$_);
3767     }
3768     $xls_r++;
3769   }
3770
3771   foreach my $svc_phone ( @svc_phone ) {
3772     my @cols = map { $svc_phone->$_ } @fields;
3773     if($p->{'format'} eq 'csv') {
3774         return { 'error' => 'Unable to create CSV' } 
3775             unless $csv->combine(@cols);
3776         $content .= $csv->string;
3777     }
3778     elsif($p->{'format'} eq 'xls') {
3779         $xls_c = 0;
3780         foreach ( @cols ) {
3781             $xls->write($xls_r,$xls_c++,$_);
3782         }
3783         $xls_r++;
3784     }
3785   }
3786
3787   $xls_workbook->close() if $p->{'format'} eq 'xls';
3788   
3789   { content => $content, format => $p->{'format'}, };
3790 }
3791
3792 sub get_ticket {
3793   my $p = shift;
3794   my($context, $session, $custnum) = _custoragent_session_custnum($p);
3795   return { 'error' => $session } if $context eq 'error';
3796
3797 #  warn "$me get_ticket: initializing ticket system\n" if $DEBUG;
3798 #  FS::TicketSystem->init();
3799 #  return { 'error' => 'get_ticket configuration error' }
3800 #    if $FS::TicketSystem::system ne 'RT_Internal';
3801
3802   # check existence and ownership as part of this
3803   warn "$me get_ticket: fetching ticket\n" if $DEBUG;
3804   my $rt_session = FS::TicketSystem->session('');
3805   my $Ticket = FS::TicketSystem->get_ticket_object(
3806     $rt_session, 
3807     ticket_id => $p->{'ticket_id'},
3808     custnum => $custnum
3809   );
3810   return { 'error' => 'ticket not found' } if !$Ticket;
3811
3812   if ( length( $p->{'subject'} || '' ) ) {
3813     # subject change
3814     if ( $p->{'subject'} ne $Ticket->Subject ) {
3815       my ($val, $msg) = $Ticket->SetSubject($p->{'subject'});
3816       return { 'error' => "unable to set subject: $msg" } if !$val;
3817     }
3818   }
3819
3820   if(length($p->{'reply'})) {
3821     my @err_or_res = FS::TicketSystem->correspond_ticket(
3822       $rt_session,
3823       'ticket_id' => $p->{'ticket_id'},
3824       'content' => $p->{'reply'},
3825     );
3826
3827     return { 'error' => 'unable to reply to ticket' } 
3828     unless ( $err_or_res[0] != 0 && defined $err_or_res[2] );
3829   }
3830
3831   warn "$me get_ticket: getting ticket history\n" if $DEBUG;
3832   my $err_or_ticket = FS::TicketSystem->get_ticket(
3833     $rt_session,
3834     'ticket_id' => $p->{'ticket_id'},
3835   );
3836
3837   if ( !ref($err_or_ticket) ) { # there is no way this should ever happen
3838     warn "$me get_ticket: unsuccessful: $err_or_ticket\n"
3839       if $DEBUG;
3840     return { 'error' => $err_or_ticket };
3841   }
3842
3843   my @custs = @{$err_or_ticket->{'custs'}};
3844   my @txns = @{$err_or_ticket->{'txns'}};
3845   my @filtered_txns;
3846
3847   # superseded by check in get_ticket_object
3848   #return { 'error' => 'invalid ticket requested' } 
3849   #unless grep($_ eq $custnum, @custs);
3850
3851   foreach my $txn ( @txns ) {
3852     push @filtered_txns, $txn 
3853     if ($txn->{'type'} eq 'EmailRecord' 
3854       || $txn->{'type'} eq 'Correspond'
3855       || $txn->{'type'} eq 'Create');
3856   }
3857
3858   warn "$me get_ticket: successful: \n"
3859   if $DEBUG;
3860   return { 'error'     => '',
3861     'transactions' => \@filtered_txns,
3862     'ticket_fields' => $err_or_ticket->{'fields'},
3863     'ticket_id' => $p->{'ticket_id'},
3864   };
3865 }
3866
3867 sub adjust_ticket_priority {
3868   my $p = shift;
3869   my($context, $session, $custnum) = _custoragent_session_custnum($p);
3870   return { 'error' => $session } if $context eq 'error';
3871
3872 #  warn "$me adjust_ticket_priority: initializing ticket system\n" if $DEBUG;
3873 #  FS::TicketSystem->init;
3874   my $ss_priority = FS::TicketSystem->selfservice_priority;
3875
3876   return { 'error' => 'adjust_ticket_priority configuration error' }
3877     if $FS::TicketSystem::system ne 'RT_Internal'
3878       or !$ss_priority;
3879
3880   my $values = $p->{'values'}; #hashref, id => priority value
3881   my %ticket_error;
3882
3883   foreach my $id (keys %$values) {
3884     warn "$me adjust_ticket_priority: fetching ticket $id\n" if $DEBUG;
3885     my $Ticket = FS::TicketSystem->get_ticket_object('',
3886       'ticket_id' => $id,
3887       'custnum'   => $custnum,
3888     );
3889     if ( !$Ticket ) {
3890       $ticket_error{$id} = 'ticket not found';
3891       next;
3892     }
3893     
3894   # RT API stuff--would we gain anything by wrapping this in FS::TicketSystem?
3895   # We're not going to implement it for RT_External.
3896     my $old_value = $Ticket->FirstCustomFieldValue($ss_priority);
3897     my $new_value = $values->{$id};
3898     next if $old_value eq $new_value;
3899
3900     warn "$me adjust_ticket_priority: updating ticket $id\n" if $DEBUG;
3901
3902     # AddCustomFieldValue works fine (replacing any existing value) if it's 
3903     # a single-valued custom field, which it should be.  If it's not, you're 
3904     # doing something wrong.
3905     my ($val, $msg);
3906     if ( length($new_value) ) {
3907       ($val, $msg) = $Ticket->AddCustomFieldValue( 
3908         Field => $ss_priority,
3909         Value => $new_value,
3910       );
3911     }
3912     else {
3913       ($val, $msg) = $Ticket->DeleteCustomFieldValue(
3914         Field => $ss_priority,
3915         Value => $old_value,
3916       );
3917     }
3918
3919     $ticket_error{$id} = $msg if !$val;
3920     warn "$me adjust_ticket_priority: $id: $msg\n" if $DEBUG and !$val;
3921   }
3922   return { 'error' => '',
3923            'ticket_error' => \%ticket_error,
3924            %{ customer_info($p) } # send updated customer info back
3925          }
3926 }
3927
3928 #--
3929
3930 sub _custoragent_session_custnum {
3931   my $p = shift;
3932
3933   my($context, $session, $custnum);
3934   if ( $p->{'session_id'} ) {
3935
3936     $context = 'customer';
3937     $session = _cache->get($p->{'session_id'})
3938       or return ( 'error' => "Can't resume session" ); #better error message
3939     $custnum = $session->{'custnum'};
3940
3941   } elsif ( $p->{'agent_session_id'} ) {
3942
3943     $context = 'agent';
3944     my $agent_cache = new FS::ClientAPI_SessionCache( {
3945       'namespace' => 'FS::ClientAPI::Agent',
3946     } );
3947     $session = $agent_cache->get($p->{'agent_session_id'})
3948       or return ( 'error' => "Can't resume session" ); #better error message
3949     $custnum = $p->{'custnum'};
3950
3951   } else {
3952     $context = 'error';
3953     return ( 'error' => "Can't resume session" ); #better error message
3954   }
3955
3956   ($context, $session, $custnum);
3957
3958 }
3959
3960 1;