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