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