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