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