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