legacy invoices via self-service, RT#13656
[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 Data::Dumper;
8 use Digest::MD5 qw(md5_hex);
9 use Date::Format;
10 use Business::CreditCard;
11 use Time::Duration;
12 use Time::Local qw(timelocal_nocheck);
13 use FS::UI::Web::small_custview qw(small_custview); #less doh
14 use FS::UI::Web;
15 use FS::UI::bytecount qw( display_bytecount );
16 use FS::Conf;
17 #use FS::UID qw(dbh);
18 use FS::Record qw(qsearch qsearchs dbh);
19 use FS::Msgcat qw(gettext);
20 use FS::Misc qw(card_types);
21 use FS::Misc::DateTime qw(parse_datetime);
22 use FS::ClientAPI_SessionCache;
23 use FS::cust_svc;
24 use FS::svc_acct;
25 use FS::svc_domain;
26 use FS::svc_phone;
27 use FS::svc_external;
28 use FS::svc_dsl;
29 use FS::dsl_device;
30 use FS::part_svc;
31 use FS::cust_main;
32 use FS::cust_bill;
33 use FS::legacy_cust_bill;
34 use FS::cust_main_county;
35 use FS::cust_pkg;
36 use FS::payby;
37 use FS::acct_rt_transaction;
38 use HTML::Entities;
39 use FS::TicketSystem;
40 use Text::CSV_XS;
41 use IO::Scalar;
42 use Spreadsheet::WriteExcel;
43
44 $DEBUG = 0;
45 $me = '[FS::ClientAPI::MyAccount]';
46
47 use vars qw( @cust_main_editable_fields );
48 @cust_main_editable_fields = qw(
49   first last company address1 address2 city
50     county state zip country
51     daytime night fax mobile
52   ship_first ship_last ship_company ship_address1 ship_address2 ship_city
53     ship_state ship_zip ship_country
54     ship_daytime ship_night ship_fax ship_mobile
55   locale
56   payby payinfo payname paystart_month paystart_year payissue payip
57   ss paytype paystate stateid stateid_state
58 );
59
60 BEGIN { #preload to reduce time customer_info takes
61   if ( $FS::TicketSystem::system ) {
62     warn "$me: initializing ticket system\n" if $DEBUG;
63     FS::TicketSystem->init();
64   }
65 }
66
67 sub _cache {
68   $cache ||= new FS::ClientAPI_SessionCache( {
69                'namespace' => 'FS::ClientAPI::MyAccount',
70              } );
71 }
72
73 sub skin_info {
74   my $p = shift;
75
76   my($context, $session, $custnum) = _custoragent_session_custnum($p);
77   #return { 'error' => $session } if $context eq 'error';
78
79   my $agentnum = '';
80   if ( $context eq 'customer' ) {
81
82     my $sth = dbh->prepare('SELECT agentnum FROM cust_main WHERE custnum = ?')
83       or die dbh->errstr;
84
85     $sth->execute($custnum) or die $sth->errstr;
86
87     $agentnum = $sth->fetchrow_arrayref->[0]
88       or die "no agentnum for custnum $custnum";
89
90   #} elsif ( $context eq 'agent' ) {
91   } elsif ( defined($p->{'agentnum'}) and $p->{'agentnum'} =~ /^(\d+)$/ ) {
92     $agentnum = $1;
93   }
94
95   my $conf = new FS::Conf;
96
97   #false laziness w/Signup.pm
98
99   my $skin_info_cache_agent = _cache->get("skin_info_cache_agent$agentnum");
100
101   if ( $skin_info_cache_agent ) {
102
103     warn "$me loading cached skin info for agentnum $agentnum\n"
104       if $DEBUG > 1;
105
106   } else {
107
108     warn "$me populating skin info cache for agentnum $agentnum\n"
109       if $DEBUG > 1;
110
111     $skin_info_cache_agent = {
112       'agentnum' => $agentnum,
113       ( map { $_ => scalar( $conf->config($_, $agentnum) ) }
114         qw( company_name date_format ) ),
115       ( map { $_ => scalar( $conf->config("selfservice-$_", $agentnum ) ) }
116         qw( body_bgcolor box_bgcolor
117             text_color link_color vlink_color hlink_color alink_color
118             font title_color title_align title_size menu_bgcolor menu_fontsize
119           )
120       ),
121       ( map { $_ => $conf->exists("selfservice-$_", $agentnum ) }
122         qw( menu_skipblanks menu_skipheadings menu_nounderline )
123       ),
124       ( map { $_ => scalar($conf->config_binary("selfservice-$_", $agentnum)) }
125         qw( title_left_image title_right_image
126             menu_top_image menu_body_image menu_bottom_image
127           )
128       ),
129       'logo' => scalar($conf->config_binary('logo.png', $agentnum )),
130       ( map { $_ => join("\n", $conf->config("selfservice-$_", $agentnum ) ) }
131         qw( head body_header body_footer company_address ) ),
132     };
133
134     _cache->set("skin_info_cache_agent$agentnum", $skin_info_cache_agent);
135
136   }
137
138   #{ %$skin_info_cache_agent };
139   $skin_info_cache_agent;
140
141 }
142
143 sub login_info {
144   my $p = shift;
145
146   my $conf = new FS::Conf;
147
148   my %info = (
149     %{ skin_info($p) },
150     'phone_login'  => $conf->exists('selfservice_server-phone_login'),
151     'single_domain'=> scalar($conf->config('selfservice_server-single_domain')),
152   );
153
154   return \%info;
155
156 }
157
158 #false laziness w/FS::ClientAPI::passwd::passwd
159 sub login {
160   my $p = shift;
161
162   my $conf = new FS::Conf;
163
164   my $svc_x = '';
165   if ( $p->{'domain'} eq 'svc_phone'
166        && $conf->exists('selfservice_server-phone_login') ) { 
167
168     my $svc_phone = qsearchs( 'svc_phone', { 'phonenum' => $p->{'username'} } );
169     return { error => 'Number not found.' } unless $svc_phone;
170
171     #XXX?
172     #my $pkg_svc = $svc_acct->cust_svc->pkg_svc;
173     #return { error => 'Only primary user may log in.' } 
174     #  if $conf->exists('selfservice_server-primary_only')
175     #    && ( ! $pkg_svc || $pkg_svc->primary_svc ne 'Y' );
176
177     return { error => 'Incorrect PIN.' }
178       unless $svc_phone->check_pin($p->{'password'});
179
180     $svc_x = $svc_phone;
181
182   } else {
183
184     my $svc_domain = qsearchs('svc_domain', { 'domain' => $p->{'domain'} } )
185       or return { error => 'Domain '. $p->{'domain'}. ' not found' };
186
187     my $svc_acct = qsearchs( 'svc_acct', { 'username'  => $p->{'username'},
188                                            'domsvc'    => $svc_domain->svcnum, }
189                            );
190     return { error => 'User not found.' } unless $svc_acct;
191
192     if($conf->exists('selfservice_server-login_svcpart')) {
193         my @svcpart = $conf->config('selfservice_server-login_svcpart');
194         my $svcpart = $svc_acct->cust_svc->svcpart;
195         return { error => 'Invalid user.' } 
196             unless grep($_ eq $svcpart, @svcpart);
197     }
198
199     return { error => 'Incorrect password.' }
200       unless $svc_acct->check_password($p->{'password'});
201
202     $svc_x = $svc_acct;
203
204   }
205
206   my $session = {
207     'svcnum' => $svc_x->svcnum,
208   };
209
210   my $cust_svc = $svc_x->cust_svc;
211   my $cust_pkg = $cust_svc->cust_pkg;
212   if ( $cust_pkg ) {
213     my $cust_main = $cust_pkg->cust_main;
214     $session->{'custnum'} = $cust_main->custnum;
215     if ( $conf->exists('pkg-balances') ) {
216       my @cust_pkg = grep { $_->part_pkg->freq !~ /^(0|$)/ }
217                           $cust_main->ncancelled_pkgs;
218       $session->{'pkgnum'} = $cust_pkg->pkgnum
219         if scalar(@cust_pkg) > 1;
220     }
221   }
222
223   #my $pkg_svc = $svc_acct->cust_svc->pkg_svc;
224   #return { error => 'Only primary user may log in.' } 
225   #  if $conf->exists('selfservice_server-primary_only')
226   #    && ( ! $pkg_svc || $pkg_svc->primary_svc ne 'Y' );
227   my $part_pkg = $cust_pkg->part_pkg;
228   return { error => 'Only primary user may log in.' }
229     if $conf->exists('selfservice_server-primary_only')
230        && $cust_svc->svcpart != $part_pkg->svcpart([qw( svc_acct svc_phone )]);
231
232   my $session_id;
233   do {
234     $session_id = md5_hex(md5_hex(time(). {}. rand(). $$))
235   } until ( ! defined _cache->get($session_id) ); #just in case
236
237   my $timeout = $conf->config('selfservice-session_timeout') || '1 hour';
238   _cache->set( $session_id, $session, $timeout );
239
240   return { 'error'      => '',
241            'session_id' => $session_id,
242          };
243 }
244
245 sub logout {
246   my $p = shift;
247   if ( $p->{'session_id'} ) {
248     _cache->remove($p->{'session_id'});
249     return { %{ skin_info($p) }, 'error' => '' };
250   } else {
251     return { %{ skin_info($p) }, 'error' => "Can't resume session" }; #better error message
252   }
253 }
254
255 sub switch_acct {
256   my $p = shift;
257
258   my($context, $session, $custnum) = _custoragent_session_custnum($p);
259   return { 'error' => $session } if $context eq 'error';
260
261   my $svc_acct = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_acct' )
262     or return { 'error' => "Service not found" };
263
264   $session->{'svcnum'} = $svc_acct->svcnum;
265
266   my $conf = new FS::Conf;
267   my $timeout = $conf->config('selfservice-session_timeout') || '1 hour';
268   _cache->set( $p->{'session_id'}, $session, $timeout );
269
270   return { 'error' => '' };
271
272 }
273
274 sub payment_gateway {
275   # internal use only
276   # takes a cust_main and a cust_payby entry, returns the payment_gateway
277   my $conf = new FS::Conf;
278   my $cust_main = shift;
279   my $cust_payby = shift;
280   my $gatewaynum = $conf->config('selfservice-payment_gateway');
281   if ( $gatewaynum ) {
282     my $pg = qsearchs('payment_gateway', { gatewaynum => $gatewaynum });
283     die "configured gatewaynum $gatewaynum not found!" if !$pg;
284     return $pg;
285   }
286   else {
287     return '' if ! FS::payby->realtime($cust_payby);
288     my $pg = $cust_main->agent->payment_gateway(
289       'method'  => FS::payby->payby2bop($cust_payby),
290       'nofatal' => 1
291     );
292     return $pg;
293   }
294 }
295
296 sub access_info {
297   my $p = shift;
298
299   my $conf = new FS::Conf;
300
301   my $info = skin_info($p);
302
303   use vars qw( $cust_paybys ); #cache for performance
304   unless ( $cust_paybys ) {
305
306     my %cust_paybys = map { $_ => 1 }
307                       map { FS::payby->payby2payment($_) }
308                           $conf->config('signup_server-payby');
309
310     $cust_paybys = [ keys %cust_paybys ];
311
312   }
313   $info->{'cust_paybys'} = $cust_paybys;
314
315   my($context, $session, $custnum) = _custoragent_session_custnum($p);
316   return { 'error' => $session } if $context eq 'error';
317
318   my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
319     or return { 'error' => "unknown custnum $custnum" };
320
321   $info->{'hide_payment_fields'} = [ 
322     map { 
323       my $pg = payment_gateway($cust_main, $_);
324       $pg && $pg->gateway_namespace eq 'Business::OnlineThirdPartyPayment';
325     } @{ $info->{cust_paybys} }
326   ];
327
328   $info->{'self_suspend_reason'} = 
329       $conf->config('selfservice-self_suspend_reason', $cust_main->agentnum);
330
331   $info->{'edit_ticket_subject'} =
332       $conf->exists('ticket_system-selfservice_edit_subject') && 
333       $cust_main->edit_subject;
334
335   return { %$info,
336            'custnum'       => $custnum,
337            'access_pkgnum' => $session->{'pkgnum'},
338            'access_svcnum' => $session->{'svcnum'},
339          };
340 }
341
342 sub customer_info {
343   my $p = shift;
344
345   my($context, $session, $custnum) = _custoragent_session_custnum($p);
346   return { 'error' => $session } if $context eq 'error';
347
348   my %return;
349
350   my $conf = new FS::Conf;
351   if ($conf->exists('cust_main-require_address2')) {
352     $return{'require_address2'} = '1';
353   }else{
354     $return{'require_address2'} = '';
355   }
356
357   if ( $FS::TicketSystem::system ) {
358     warn "$me customer_info: initializing ticket system\n" if $DEBUG;
359     FS::TicketSystem->init();
360   }
361  
362   if ( $custnum ) { #customer record
363
364     my $search = { 'custnum' => $custnum };
365     $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
366     my $cust_main = qsearchs('cust_main', $search )
367       or return { 'error' => "unknown custnum $custnum" };
368
369     if ( $session->{'pkgnum'} ) { 
370       $return{balance} = $cust_main->balance_pkgnum( $session->{'pkgnum'} );
371     } else {
372       $return{balance} = $cust_main->balance;
373     }
374
375     my @tickets = $cust_main->tickets;
376     # unavoidable false laziness w/ httemplate/view/cust_main/tickets.html
377     if ( FS::TicketSystem->selfservice_priority ) {
378       my $dir = $conf->exists('ticket_system-priority_reverse') ? -1 : 1;
379       $return{tickets} = [ 
380         sort { 
381           (
382             ($a->{'_selfservice_priority'} eq '') <=>
383             ($b->{'_selfservice_priority'} eq '')
384           ) ||
385           ( $dir * 
386             ($b->{'_selfservice_priority'} <=> $a->{'_selfservice_priority'}) 
387           )
388         } @tickets
389       ];
390     }
391     else {
392       $return{tickets} = \@tickets;
393     }
394
395     unless ( $session->{'pkgnum'} ) {
396       my @open = map {
397                        {
398                          invnum => $_->invnum,
399                          date   => time2str("%b %o, %Y", $_->_date),
400                          owed   => $_->owed,
401                        };
402                      } $cust_main->open_cust_bill;
403       $return{open_invoices} = \@open;
404     }
405
406     $return{small_custview} =
407       small_custview( $cust_main,
408                       scalar($conf->config('countrydefault')),
409                       ( $session->{'pkgnum'} ? 1 : 0 ), #nobalance
410                     );
411
412     $return{name} = $cust_main->first. ' '. $cust_main->get('last');
413     $return{ship_name} = $cust_main->ship_first. ' '. $cust_main->get('ship_last');
414
415     for (@cust_main_editable_fields) {
416       $return{$_} = $cust_main->get($_);
417     }
418
419     if ( $cust_main->payby =~ /^(CARD|DCRD)$/ ) {
420       $return{payinfo} = $cust_main->paymask;
421       @return{'month', 'year'} = $cust_main->paydate_monthyear;
422     }
423
424     $return{'invoicing_list'} =
425       join(', ', grep { $_ !~ /^(POST|FAX)$/ } $cust_main->invoicing_list );
426     $return{'postal_invoicing'} =
427       0 < ( grep { $_ eq 'POST' } $cust_main->invoicing_list );
428
429     if (scalar($conf->config('support_packages'))) {
430       my @support_services = ();
431       foreach ($cust_main->support_services) {
432         my $seconds = $_->svc_x->seconds;
433         my $time_remaining = (($seconds < 0) ? '-' : '' ).
434                              int(abs($seconds)/3600)."h".
435                              sprintf("%02d",(abs($seconds)%3600)/60)."m";
436         my $cust_pkg = $_->cust_pkg;
437         my $pkgnum = '';
438         my $pkg = '';
439         $pkgnum = $cust_pkg->pkgnum if $cust_pkg;
440         $pkg = $cust_pkg->part_pkg->pkg if $cust_pkg;
441         push @support_services, { svcnum => $_->svcnum,
442                                   time => $time_remaining,
443                                   pkgnum => $pkgnum,
444                                   pkg => $pkg,
445                                 };
446       }
447       $return{support_services} = \@support_services;
448     }
449
450     if ( $conf->config('prepayment_discounts-credit_type') ) {
451       #need to eval?
452       $return{discount_terms_hash} = { $cust_main->discount_terms_hash };
453     }
454
455     if ( $session->{'svcnum'} ) {
456       my $cust_svc = qsearchs('cust_svc', { 'svcnum' => $session->{'svcnum'} });
457       $return{'svc_label'} = ($cust_svc->label)[1] if $cust_svc;
458       $return{'svcnum'} = $session->{'svcnum'};
459     }
460
461   } elsif ( $session->{'svcnum'} ) { #no customer record
462
463     my $svc_acct = qsearchs('svc_acct', { 'svcnum' => $session->{'svcnum'} } )
464       or die "unknown svcnum";
465     $return{name} = $svc_acct->email;
466
467   } else {
468
469     return { 'error' => 'Expired session' }; #XXX redirect to login w/this err!
470
471   }
472
473   return { 'error'          => '',
474            'custnum'        => $custnum,
475            %return,
476          };
477
478 }
479
480 sub customer_info_short {
481   my $p = shift;
482
483   my($context, $session, $custnum) = _custoragent_session_custnum($p);
484   return { 'error' => $session } if $context eq 'error';
485
486   my %return;
487
488   my $conf = new FS::Conf;
489
490   if ( $custnum ) { #customer record
491
492     my $search = { 'custnum' => $custnum };
493     $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
494     my $cust_main = qsearchs('cust_main', $search )
495       or return { 'error' => "unknown custnum $custnum" };
496
497     $return{small_custview} =
498       small_custview( $cust_main,
499                       scalar($conf->config('countrydefault')),
500                       1, ##nobalance
501                     );
502
503     $return{name} = $cust_main->first. ' '. $cust_main->get('last');
504     $return{ship_name} = $cust_main->ship_first. ' '. $cust_main->get('ship_last');
505
506     $return{payby} = $cust_main->payby;
507
508     #none of these are terribly expensive if we want 'em...
509     for (@cust_main_editable_fields) {
510       $return{$_} = $cust_main->get($_);
511     }
512     
513     if ( $cust_main->payby =~ /^(CARD|DCRD)$/ ) {
514       $return{payinfo} = $cust_main->paymask;
515       @return{'month', 'year'} = $cust_main->paydate_monthyear;
516     }
517     
518     $return{'invoicing_list'} =
519       join(', ', grep { $_ !~ /^(POST|FAX)$/ } $cust_main->invoicing_list );
520     #$return{'postal_invoicing'} =
521     #  0 < ( grep { $_ eq 'POST' } $cust_main->invoicing_list );
522
523     if ( $session->{'svcnum'} ) {
524       my $cust_svc = qsearchs('cust_svc', { 'svcnum' => $session->{'svcnum'} });
525       $return{'svc_label'} = ($cust_svc->label)[1] if $cust_svc;
526       $return{'svcnum'} = $session->{'svcnum'};
527     }
528
529   } elsif ( $session->{'svcnum'} ) { #no customer record
530
531     #uuh, not supproted yet... die?
532     return { 'error' => 'customer_info_short not yet supported as agent' };
533
534   } else {
535
536     return { 'error' => 'Expired session' }; #XXX redirect to login w/this err!
537
538   }
539
540   return { 'error'          => '',
541            'custnum'        => $custnum,
542            %return,
543          };
544 }
545
546 sub edit_info {
547   my $p = shift;
548   my $session = _cache->get($p->{'session_id'})
549     or return { 'error' => "Can't resume session" }; #better error message
550
551   my $custnum = $session->{'custnum'}
552     or return { 'error' => "no customer record" };
553
554   my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
555     or return { 'error' => "unknown custnum $custnum" };
556
557   my $new = new FS::cust_main { $cust_main->hash };
558   $new->set( $_ => $p->{$_} )
559     foreach grep { exists $p->{$_} } @cust_main_editable_fields;
560
561   my $payby = '';
562   if (exists($p->{'payby'})) {
563     $p->{'payby'} =~ /^([A-Z]{4})$/
564       or return { 'error' => "illegal_payby " . $p->{'payby'} };
565     $payby = $1;
566   }
567
568   if ( $payby =~ /^(CARD|DCRD)$/ ) {
569
570     $new->paydate($p->{'year'}. '-'. $p->{'month'}. '-01');
571
572     if ( $new->payinfo eq $cust_main->paymask ) {
573       $new->payinfo($cust_main->payinfo);
574     } else {
575       $new->payinfo($p->{'payinfo'});
576     }
577
578     $new->set( 'payby' => $p->{'auto'} ? 'CARD' : 'DCRD' );
579
580   } elsif ( $payby =~ /^(CHEK|DCHK)$/ ) {
581
582     my $payinfo;
583     $p->{'payinfo1'} =~ /^([\dx]+)$/
584       or return { 'error' => "illegal account number ". $p->{'payinfo1'} };
585     my $payinfo1 = $1;
586      $p->{'payinfo2'} =~ /^([\dx\.]+)$/ # . turned on by -require-bank-branch?
587       or return { 'error' => "illegal ABA/routing number ". $p->{'payinfo2'} };
588     my $payinfo2 = $1;
589     $payinfo = $payinfo1. '@'. $payinfo2;
590
591     $new->payinfo( ($payinfo eq $cust_main->paymask)
592                      ? $cust_main->payinfo
593                      : $payinfo
594                  );
595
596     $new->set( 'payby' => $p->{'auto'} ? 'CHEK' : 'DCHK' );
597
598   } elsif ( $payby =~ /^(BILL)$/ ) {
599     #no-op
600   } elsif ( $payby ) {  #notyet ready
601     return { 'error' => "unknown payby $payby" };
602   }
603
604   my @invoicing_list;
605   if ( exists $p->{'invoicing_list'} || exists $p->{'postal_invoicing'} ) {
606     #false laziness with httemplate/edit/process/cust_main.cgi
607     @invoicing_list = split( /\s*\,\s*/, $p->{'invoicing_list'} );
608     push @invoicing_list, 'POST' if $p->{'postal_invoicing'};
609   } else {
610     @invoicing_list = $cust_main->invoicing_list;
611   }
612
613   my $error = $new->replace($cust_main, \@invoicing_list);
614   return { 'error' => $error } if $error;
615   #$cust_main = $new;
616   
617   return { 'error' => '' };
618 }
619
620 sub payment_info {
621   my $p = shift;
622   my $session = _cache->get($p->{'session_id'})
623     or return { 'error' => "Can't resume session" }; #better error message
624
625   ##
626   #generic
627   ##
628
629   my $conf = new FS::Conf;
630   use vars qw($payment_info); #cache for performance
631   unless ( $payment_info ) {
632
633     my %states = map { $_->state => 1 }
634                    qsearch('cust_main_county', {
635                      'country' => $conf->config('countrydefault') || 'US'
636                    } );
637
638     my %cust_paybys = map { $_ => 1 }
639                       map { FS::payby->payby2payment($_) }
640                           $conf->config('signup_server-payby');
641
642     my @cust_paybys = keys %cust_paybys;
643
644     $payment_info = {
645
646       #list all counties/states/countries
647       'cust_main_county' => 
648         [ map { $_->hashref } qsearch('cust_main_county', {}) ],
649
650       #shortcut for one-country folks
651       'states' =>
652         [ sort { $a cmp $b } keys %states ],
653
654       'card_types' => card_types(),
655
656       'paytypes' => [ @FS::cust_main::paytypes ],
657
658       'paybys' => [ $conf->config('signup_server-payby') ],
659       'cust_paybys' => \@cust_paybys,
660
661       'stateid_label' => FS::Msgcat::_gettext('stateid'),
662       'stateid_state_label' => FS::Msgcat::_gettext('stateid_state'),
663
664       'show_ss'  => $conf->exists('show_ss'),
665       'show_stateid' => $conf->exists('show_stateid'),
666       'show_paystate' => $conf->exists('show_bankstate'),
667
668       'save_unchecked' => $conf->exists('selfservice-save_unchecked'),
669
670       'credit_card_surcharge_percentage' => $conf->config('credit-card-surcharge-percentage'),
671     };
672
673   }
674
675   ##
676   #customer-specific
677   ##
678
679   my %return = %$payment_info;
680
681   my $custnum = $session->{'custnum'};
682
683   my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
684     or return { 'error' => "unknown custnum $custnum" };
685
686   $return{'hide_payment_fields'} = [
687     map { 
688       my $pg = payment_gateway($cust_main, $_);
689       $pg && $pg->gateway_namespace eq 'Business::OnlineThirdPartyPayment';
690     } @{ $return{cust_paybys} }
691   ];
692
693   $return{balance} = $cust_main->balance; #XXX pkg-balances?
694
695   $return{payname} = $cust_main->payname
696                      || ( $cust_main->first. ' '. $cust_main->get('last') );
697
698   $return{$_} = $cust_main->get($_) for qw(address1 address2 city state zip);
699
700   $return{payby} = $cust_main->payby;
701   $return{stateid_state} = $cust_main->stateid_state;
702
703   if ( $cust_main->payby =~ /^(CARD|DCRD)$/ ) {
704     $return{card_type} = cardtype($cust_main->payinfo);
705     $return{payinfo} = $cust_main->paymask;
706
707     @return{'month', 'year'} = $cust_main->paydate_monthyear;
708
709   }
710
711   if ( $cust_main->payby =~ /^(CHEK|DCHK)$/ ) {
712     my ($payinfo1, $payinfo2) = split '@', $cust_main->paymask;
713     $return{payinfo1} = $payinfo1;
714     $return{payinfo2} = $payinfo2;
715     $return{paytype}  = $cust_main->paytype;
716     $return{paystate} = $cust_main->paystate;
717
718   }
719
720   if ( $conf->config('prepayment_discounts-credit_type') ) {
721     #need to eval?
722     $return{discount_terms_hash} = { $cust_main->discount_terms_hash };
723   }
724
725   #doubleclick protection
726   my $_date = time;
727   $return{paybatch} = "webui-MyAccount-$_date-$$-". rand() * 2**32;
728
729   return { 'error' => '',
730            %return,
731          };
732
733 }
734
735 #some false laziness with httemplate/process/payment.cgi - look there for
736 #ACH and CVV support stuff
737
738 sub validate_payment {
739   my $p = shift;
740
741   my $session = _cache->get($p->{'session_id'})
742     or return { 'error' => "Can't resume session" }; #better error message
743
744   my $custnum = $session->{'custnum'};
745
746   my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
747     or return { 'error' => "unknown custnum $custnum" };
748
749   $p->{'amount'} =~ /^\s*(\d+(\.\d{2})?)\s*$/
750     or return { 'error' => gettext('illegal_amount') };
751   my $amount = $1;
752   return { error => 'Amount must be greater than 0' } unless $amount > 0;
753
754   $p->{'discount_term'} =~ /^\s*(\d*)\s*$/
755     or return { 'error' => gettext('illegal_discount_term'). ': '. $p->{'discount_term'} };
756   my $discount_term = $1;
757
758   $p->{'payname'} =~ /^([\w \,\.\-\']+)$/
759     or return { 'error' => gettext('illegal_name'). " payname: ". $p->{'payname'} };
760   my $payname = $1;
761
762   $p->{'paybatch'} =~ /^([\w \!\@\#\$\%\&\(\)\-\+\;\:\'\"\,\.\?\/\=]*)$/
763     or return { 'error' => gettext('illegal_text'). " paybatch: ". $p->{'paybatch'} };
764   my $paybatch = $1;
765
766   $p->{'payby'} ||= 'CARD';
767   $p->{'payby'} =~ /^([A-Z]{4})$/
768     or return { 'error' => "illegal_payby " . $p->{'payby'} };
769   my $payby = $1;
770
771   #false laziness w/process/payment.cgi
772   my $payinfo;
773   my $paycvv = '';
774   if ( $payby eq 'CHEK' || $payby eq 'DCHK' ) {
775   
776     $p->{'payinfo1'} =~ /^([\dx]+)$/
777       or return { 'error' => "illegal account number ". $p->{'payinfo1'} };
778     my $payinfo1 = $1;
779      $p->{'payinfo2'} =~ /^([\dx]+)$/
780       or return { 'error' => "illegal ABA/routing number ". $p->{'payinfo2'} };
781     my $payinfo2 = $1;
782     $payinfo = $payinfo1. '@'. $payinfo2;
783
784     $payinfo = $cust_main->payinfo
785       if $cust_main->paymask eq $payinfo;
786    
787   } elsif ( $payby eq 'CARD' || $payby eq 'DCRD' ) {
788    
789     $payinfo = $p->{'payinfo'};
790
791     #more intelligent mathing will be needed here if you change
792     #card_masking_method and don't remove existing paymasks
793     $payinfo = $cust_main->payinfo
794       if $cust_main->paymask eq $payinfo;
795
796     $payinfo =~ s/\D//g;
797     $payinfo =~ /^(\d{13,16}|\d{8,9})$/
798       or return { 'error' => gettext('invalid_card') }; # . ": ". $self->payinfo
799     $payinfo = $1;
800
801     validate($payinfo)
802       or return { 'error' => gettext('invalid_card') }; # . ": ". $self->payinfo
803     return { 'error' => gettext('unknown_card_type') }
804       if $payinfo !~ /^99\d{14}$/ && cardtype($payinfo) eq "Unknown";
805
806     if ( length($p->{'paycvv'}) && $p->{'paycvv'} !~ /^\s*$/ ) {
807       if ( cardtype($payinfo) eq 'American Express card' ) {
808         $p->{'paycvv'} =~ /^\s*(\d{4})\s*$/
809           or return { 'error' => "CVV2 (CID) for American Express cards is four digits." };
810         $paycvv = $1;
811       } else {
812         $p->{'paycvv'} =~ /^\s*(\d{3})\s*$/
813           or return { 'error' => "CVV2 (CVC2/CID) is three digits." };
814         $paycvv = $1;
815       }
816     }
817   
818   } else {
819     die "unknown payby $payby";
820   }
821
822   my %payby2fields = (
823     'CARD' => [ qw( paystart_month paystart_year payissue payip
824                     address1 address2 city state zip country    ) ],
825     'CHEK' => [ qw( ss paytype paystate stateid stateid_state payip ) ],
826   );
827
828   my $card_type = '';
829   $card_type = cardtype($payinfo) if $payby eq 'CARD';
830
831   { 
832     'cust_main'      => $cust_main, #XXX or just custnum??
833     'amount'         => $amount,
834     'payby'          => $payby,
835     'payinfo'        => $payinfo,
836     'paymask'        => $cust_main->mask_payinfo( $payby, $payinfo ),
837     'card_type'      => $card_type,
838     'paydate'        => $p->{'year'}. '-'. $p->{'month'}. '-01',
839     'paydate_pretty' => $p->{'month'}. ' / '. $p->{'year'},
840     'payname'        => $payname,
841     'paybatch'       => $paybatch, #this doesn't actually do anything
842     'paycvv'         => $paycvv,
843     'payname'        => $payname,
844     'discount_term'  => $discount_term,
845     'pkgnum'         => $session->{'pkgnum'},
846     map { $_ => $p->{$_} } ( @{ $payby2fields{$payby} },
847                              qw( save auto ),
848                            )
849   };
850
851 }
852
853 sub store_payment {
854   my $p = shift;
855
856   my $validate = validate_payment($p);
857   return $validate if $validate->{'error'};
858
859   my $conf = new FS::Conf;
860   my $timeout = $conf->config('selfservice-session_timeout') || '1 hour'; #?
861   _cache->set( 'payment_'.$p->{'session_id'}, $validate, $timeout );
862
863   +{ map { $_=>$validate->{$_} }
864       qw( card_type paymask payname paydate_pretty amount )
865   };
866
867 }
868
869 sub process_stored_payment {
870   my $p = shift;
871
872   my $session_id = $p->{'session_id'};
873
874   my $payment_info = _cache->get( "payment_$session_id" )
875     or return { 'error' => "Can't resume session" }; #better error message
876
877   do_process_payment($payment_info);
878
879 }
880
881 sub process_payment {
882   my $p = shift;
883
884   my $payment_info = validate_payment($p);
885   return $payment_info if $payment_info->{'error'};
886
887   do_process_payment($payment_info);
888
889 }
890
891 sub do_process_payment {
892   my $validate = shift;
893
894   my $cust_main = $validate->{'cust_main'};
895
896   my $amount = delete $validate->{'amount'};
897   my $paynum = '';
898
899   my $payby = delete $validate->{'payby'};
900
901   my $error = $cust_main->realtime_bop( $FS::payby::payby2bop{$payby}, $amount,
902     'quiet'       => 1,
903     'selfservice' => 1,
904     'paynum_ref'  => \$paynum,
905     %$validate,
906   );
907   return { 'error' => $error } if $error;
908
909   $cust_main->apply_payments;
910
911   if ( $validate->{'save'} ) {
912     my $new = new FS::cust_main { $cust_main->hash };
913     if ($validate->{'payby'} eq 'CARD' || $validate->{'payby'} eq 'DCRD') {
914       $new->set( $_ => $validate->{$_} )
915         foreach qw( payname paystart_month paystart_year payissue payip
916                     address1 address2 city state zip country );
917       $new->set( 'payby' => $validate->{'auto'} ? 'CARD' : 'DCRD' );
918     } elsif ($payby eq 'CHEK' || $payby eq 'DCHK') {
919       $new->set( $_ => $validate->{$_} )
920         foreach qw( payname payip paytype paystate
921                     stateid stateid_state );
922       $new->set( 'payby' => $validate->{'auto'} ? 'CHEK' : 'DCHK' );
923     }
924     $new->set( 'payinfo' => $cust_main->card_token || $validate->{'payinfo'} );
925     $new->set( 'paydate' => $validate->{'paydate'} );
926     my $error = $new->replace($cust_main);
927     if ( $error ) {
928       #no, this causes customers to process their payments again
929       #return { 'error' => $error };
930       #XXX just warn verosely for now so i can figure out how these happen in
931       # the first place, eventually should redirect them to the "change
932       #address" page but indicate the payment did process??
933       delete($validate->{'payinfo'}); #don't want to log this!
934       warn "WARNING: error changing customer info when processing payment (not returning to customer as a processing error): $error\n".
935            "NEW: ". Dumper($new)."\n".
936            "OLD: ". Dumper($cust_main)."\n".
937            "PACKET: ". Dumper($validate)."\n";
938     #} else {
939       #not needed...
940       #$cust_main = $new;
941     }
942   }
943
944   my $cust_pay = '';
945   my $receipt_html = '';
946   if ($paynum) {
947       # currently supported for realtime CC only; send receipt data to SS
948       $cust_pay = qsearchs('cust_pay', { 'paynum' => $paynum } );
949       if($cust_pay) {
950         $receipt_html = qq!
951 <TABLE BGCOLOR="#cccccc" BORDER=0 CELLSPACING=2>
952
953 <TR>
954   <TD ALIGN="right">Payment#</TD>
955   <TD BGCOLOR="#FFFFFF"><B>! . $cust_pay->paynum . qq!</B></TD>
956 </TR>
957
958 <TR>
959   <TD ALIGN="right">Date</TD>
960
961   <TD BGCOLOR="#FFFFFF"><B>! . 
962         time2str("%a&nbsp;%b&nbsp;%o,&nbsp;%Y&nbsp;%r", $cust_pay->_date)
963                                                             . qq!</B></TD>
964 </TR>
965
966
967 <TR>
968   <TD ALIGN="right">Amount</TD>
969   <TD BGCOLOR="#FFFFFF"><B>! . sprintf('%.2f', $cust_pay->paid) . qq!</B></TD>
970
971 </TR>
972
973 <TR>
974   <TD ALIGN="right">Payment method</TD>
975   <TD BGCOLOR="#FFFFFF"><B>! . $cust_pay->payby_name .' #'. $cust_pay->paymask
976                                                                 . qq!</B></TD>
977 </TR>
978
979 </TABLE>
980 !;
981       }
982   }
983
984   if ( $cust_pay ) {
985
986     my($gw, $auth, $order) = split(':', $cust_pay->paybatch);
987
988     return {
989       'error'        => '',
990       'amount'       => sprintf('%.2f', $cust_pay->paid),
991       'date'         => $cust_pay->_date,
992       'date_pretty'  => time2str('%Y-%m-%d', $cust_pay->_date),
993       'time_pretty'  => time2str('%T', $cust_pay->_date),
994       'auth_num'     => $auth,
995       'order_num'    => $order,
996       'receipt_html' => $receipt_html,
997     };
998
999   } else {
1000
1001     return {
1002       'error'        => '',
1003       'receipt_html' => '',
1004     };
1005
1006   }
1007
1008 }
1009
1010 sub realtime_collect {
1011   my $p = shift;
1012
1013   my $session = _cache->get($p->{'session_id'})
1014     or return { 'error' => "Can't resume session" }; #better error message
1015
1016   my $custnum = $session->{'custnum'};
1017
1018   my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1019     or return { 'error' => "unknown custnum $custnum" };
1020
1021   my $amount;
1022   if ( $p->{'amount'} ) {
1023     $amount = $p->{'amount'};
1024   }
1025   elsif ( $session->{'pkgnum'} ) {
1026     $amount = $cust_main->balance_pkgnum( $session->{'pkgnum'} );
1027   }
1028   else {
1029     $amount = $cust_main->balance;
1030   }
1031
1032   my $error = $cust_main->realtime_collect(
1033     'method'     => $p->{'method'},
1034     'amount'     => $amount,
1035     'pkgnum'     => $session->{'pkgnum'},
1036     'session_id' => $p->{'session_id'},
1037     'apply'      => 1,
1038     'selfservice'=> 1,
1039   );
1040   return { 'error' => $error } unless ref( $error );
1041
1042   return { 'error' => '', amount => $amount, %$error };
1043 }
1044
1045 sub process_payment_order_pkg {
1046   my $p = shift;
1047
1048   my $hr = process_payment($p);
1049   return $hr if $hr->{'error'};
1050
1051   order_pkg($p);
1052 }
1053
1054 sub process_payment_order_renew {
1055   my $p = shift;
1056
1057   my $hr = process_payment($p);
1058   return $hr if $hr->{'error'};
1059
1060   order_renew($p);
1061 }
1062
1063 sub process_prepay {
1064
1065   my $p = shift;
1066
1067   my $session = _cache->get($p->{'session_id'})
1068     or return { 'error' => "Can't resume session" }; #better error message
1069
1070   my %return;
1071
1072   my $custnum = $session->{'custnum'};
1073
1074   my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1075     or return { 'error' => "unknown custnum $custnum" };
1076
1077   my( $amount, $seconds, $upbytes, $downbytes, $totalbytes ) = ( 0, 0, 0, 0, 0 );
1078   my $error = $cust_main->recharge_prepay( $p->{'prepaid_cardnum'},
1079                                            \$amount,
1080                                            \$seconds,
1081                                            \$upbytes,
1082                                            \$downbytes,
1083                                            \$totalbytes,
1084                                          );
1085
1086   return { 'error' => $error } if $error;
1087
1088   return { 'error'     => '',
1089            'amount'    => $amount,
1090            'seconds'   => $seconds,
1091            'duration'  => duration_exact($seconds),
1092            'upbytes'   => $upbytes,
1093            'upload'    => FS::UI::bytecount::bytecount_unexact($upbytes),
1094            'downbytes' => $downbytes,
1095            'download'  => FS::UI::bytecount::bytecount_unexact($downbytes),
1096            'totalbytes'=> $totalbytes,
1097            'totalload' => FS::UI::bytecount::bytecount_unexact($totalbytes),
1098          };
1099
1100 }
1101
1102 sub invoice {
1103   my $p = shift;
1104   my $session = _cache->get($p->{'session_id'})
1105     or return { 'error' => "Can't resume session" }; #better error message
1106
1107   my $custnum = $session->{'custnum'};
1108
1109   my $invnum = $p->{'invnum'};
1110
1111   my $cust_bill = qsearchs('cust_bill', { 'invnum'  => $invnum,
1112                                           'custnum' => $custnum } )
1113     or return { 'error' => "Can't find invnum" };
1114
1115   #my %return;
1116
1117   return { 'error'        => '',
1118            'invnum'       => $invnum,
1119            'invoice_text' => join('', $cust_bill->print_text ),
1120            'invoice_html' => $cust_bill->print_html( { unsquelch_cdr => 1 } ),
1121          };
1122
1123 }
1124
1125 sub invoice_pdf {
1126   my $p = shift;
1127   my $session = _cache->get($p->{'session_id'})
1128     or return { 'error' => "Can't resume session" }; #better error message
1129
1130   my $custnum = $session->{'custnum'};
1131
1132   my $invnum = $p->{'invnum'};
1133
1134   my $cust_bill = qsearchs('cust_bill', { 'invnum'  => $invnum,
1135                                           'custnum' => $custnum } )
1136     or return { 'error' => "Can't find invnum" };
1137
1138   #my %return;
1139
1140   return { 'error'       => '',
1141            'invnum'      => $invnum,
1142            'invoice_pdf' => $cust_bill->print_pdf( { unsquelch_cdr => 1 } ),
1143          };
1144
1145 }
1146
1147 sub legacy_invoice {
1148   my $p = shift;
1149   my $session = _cache->get($p->{'session_id'})
1150     or return { 'error' => "Can't resume session" }; #better error message
1151
1152   my $custnum = $session->{'custnum'};
1153
1154   my $legacyinvnum = $p->{'legacyinvnum'};
1155
1156   my $legacy_cust_bill = qsearchs('legacy_cust_bill', {
1157     'legacyinvnum' => $legacyinvnum,
1158     'custnum'      => $custnum,
1159   }) or return { 'error' => "Can't find legacyinvnum" };
1160
1161   #my %return;
1162
1163   return { 'error'        => '',
1164            'legacyinvnum' => $legacyinvnum,
1165            'legacyid'     => $legacy_cust_bill->legacyid,
1166            'invoice_html' => $legacy_cust_bill->content_html,
1167          };
1168
1169 }
1170
1171 sub legacy_invoice_pdf {
1172   my $p = shift;
1173   my $session = _cache->get($p->{'session_id'})
1174     or return { 'error' => "Can't resume session" }; #better error message
1175
1176   my $custnum = $session->{'custnum'};
1177
1178   my $legacyinvnum = $p->{'legacyinvnum'};
1179
1180   my $legacy_cust_bill = qsearchs('legacy_cust_bill', {
1181     'legacyinvnum' => $legacyinvnum,
1182     'custnum'      => $custnum,
1183   }) or return { 'error' => "Can't find legacyinvnum" };
1184
1185   #my %return;
1186
1187   return { 'error'        => '',
1188            'legacyinvnum' => $legacyinvnum,
1189            'legacyid'     => $legacy_cust_bill->legacyid,
1190            'invoice_pdf'  => $legacy_cust_bill->content_pdf,
1191          };
1192
1193 }
1194
1195 sub invoice_logo {
1196   my $p = shift;
1197
1198   #sessioning for this?  how do we get the session id to the backend invoice
1199   # template so it can add it to the link, blah
1200
1201   my $agentnum = '';
1202   if ( $p->{'invnum'} ) {
1203     my $cust_bill = qsearchs('cust_bill', { 'invnum' => $p->{'invnum'} } )
1204       or return { 'error' => 'unknown invnum' };
1205     $agentnum = $cust_bill->cust_main->agentnum;
1206   }
1207
1208   my $templatename = $p->{'template'} || $p->{'templatename'};
1209
1210   #false laziness-ish w/view/cust_bill-logo.cgi
1211
1212   my $conf = new FS::Conf;
1213   if ( $templatename =~ /^([^\.\/]*)$/ && $conf->exists("logo_$1.png") ) {
1214     $templatename = "_$1";
1215   } else {
1216     $templatename = '';
1217   }
1218
1219   my $filename = "logo$templatename.png";
1220
1221   return { 'error'        => '',
1222            'logo'         => $conf->config_binary($filename, $agentnum),
1223            'content_type' => 'image/png', #should allow gif, jpg too
1224          };
1225 }
1226
1227
1228 sub list_invoices {
1229   my $p = shift;
1230   my $session = _cache->get($p->{'session_id'})
1231     or return { 'error' => "Can't resume session" }; #better error message
1232
1233   my $custnum = $session->{'custnum'};
1234
1235   my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1236     or return { 'error' => "unknown custnum $custnum" };
1237
1238   my @cust_bill = $cust_main->cust_bill;
1239   my @legacy_cust_bill = $cust_main->legacy_cust_bill;
1240
1241   my $balance = 0;
1242
1243   return  { 'error'       => '',
1244             'balance'     => $cust_main->balance,
1245             'invoices'    => [
1246               map {
1247                     my $owed = $_->owed;
1248                     $balance += $owed;
1249                     +{ 'invnum'       => $_->invnum,
1250                        '_date'        => $_->_date,
1251                        'date'         => time2str("%b %o, %Y", $_->_date),
1252                        'date_short'   => time2str("%m-%d-%Y",  $_->_date),
1253                        'previous'     => sprintf('%.2f', ($_->previous)[0]),
1254                        'charged'      => sprintf('%.2f', $_->charged),
1255                        'owed'         => sprintf('%.2f', $owed),
1256                        'balance'      => sprintf('%.2f', $balance),
1257                      }
1258                   }
1259                   @cust_bill
1260             ],
1261             'legacy_invoices' => [
1262               map {
1263                     +{ 'legacyinvnum' => $_->legacyinvnum,
1264                        'legacyid'     => $_->legacyid,
1265                        '_date'        => $_->_date,
1266                        'date'         => time2str("%b %o, %Y", $_->_date),
1267                        'date_short'   => time2str("%m-%d-%Y",  $_->_date),
1268                        'charged'      => sprintf('%.2f', $_->charged),
1269                        'has_content'  => (    length($_->content_pdf)
1270                                            || length($_->content_html) ),
1271                      }
1272                   }
1273                   @legacy_cust_bill
1274             ],
1275           };
1276 }
1277
1278 sub cancel {
1279   my $p = shift;
1280   my $session = _cache->get($p->{'session_id'})
1281     or return { 'error' => "Can't resume session" }; #better error message
1282
1283   my $custnum = $session->{'custnum'};
1284
1285   my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1286     or return { 'error' => "unknown custnum $custnum" };
1287
1288   my @errors = $cust_main->cancel( 'quiet'=>1 );
1289
1290   my $error = scalar(@errors) ? join(' / ', @errors) : '';
1291
1292   return { 'error' => $error };
1293
1294 }
1295
1296 sub list_pkgs {
1297   my $p = shift;
1298
1299   my($context, $session, $custnum) = _custoragent_session_custnum($p);
1300   return { 'error' => $session } if $context eq 'error';
1301
1302   my $search = { 'custnum' => $custnum };
1303   $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
1304   my $cust_main = qsearchs('cust_main', $search )
1305     or return { 'error' => "unknown custnum $custnum" };
1306
1307   my $conf = new FS::Conf;
1308   
1309 # the duplication below is necessary:
1310 # 1. to maintain the current buggy behaviour wrt the cust_pkg and part_pkg
1311 # hashes overwriting each other (setup and no_auto fields). Fixing that is a
1312 # non-backwards-compatible change breaking the software of anyone using the API
1313 # instead of the stock selfservice
1314 # 2. to return cancelled packages as well - for wholesale and non-wholesale
1315   if( $conf->exists('selfservice_server-view-wholesale') ) {
1316     return { 'svcnum'   => $session->{'svcnum'},
1317             'custnum'  => $custnum,
1318             'cust_pkg' => [ map {
1319                           { $_->hash,
1320                             part_pkg => [ map $_->hashref, $_->part_pkg ],
1321                             part_svc =>
1322                               [ map $_->hashref, $_->available_part_svc ],
1323                             cust_svc => 
1324                               [ map { my $ref = { $_->hash,
1325                                                   label => [ $_->label ],
1326                                                 };
1327                                       $ref->{_password} = $_->svc_x->_password
1328                                         if $context eq 'agent'
1329                                         && $conf->exists('agent-showpasswords')
1330                                         && $_->part_svc->svcdb eq 'svc_acct';
1331                                       $ref;
1332                                     } $_->cust_svc
1333                               ],
1334                           };
1335                         } $cust_main->cust_pkg
1336                   ],
1337     'small_custview' =>
1338       small_custview( $cust_main, $conf->config('countrydefault') ),
1339     'wholesale_view' => 1,
1340     'login_svcpart' => [ $conf->config('selfservice_server-login_svcpart') ],
1341     'date_format' => $conf->config('date_format') || '%m/%d/%Y',
1342     'lnp' => $conf->exists('svc_phone-lnp'),
1343       };
1344   }
1345
1346   { 'svcnum'   => $session->{'svcnum'},
1347     'custnum'  => $custnum,
1348     'cust_pkg' => [ map {
1349                           my $primary_cust_svc = $_->primary_cust_svc;
1350                           +{ $_->hash,
1351                             $_->part_pkg->hash,
1352                             status => $_->status,
1353                             part_svc =>
1354                               [ map $_->hashref, $_->available_part_svc ],
1355                             cust_svc => 
1356                               [ map { my $ref = { $_->hash,
1357                                                   label => [ $_->label ],
1358                                                 };
1359                                       $ref->{_password} = $_->svc_x->_password
1360                                         if $context eq 'agent'
1361                                         && $conf->exists('agent-showpasswords')
1362                                         && $_->part_svc->svcdb eq 'svc_acct';
1363                                       $ref->{svchash} = { $_->svc_x->hash } if 
1364                                         $_->part_svc->svcdb eq 'svc_phone';
1365                                       $ref->{svchash}->{svcpart} =  $_->part_svc->svcpart
1366                                         if $_->part_svc->svcdb eq 'svc_phone'; # hack
1367                                       $ref;
1368                                     } $_->cust_svc
1369                               ],
1370                             primary_cust_svc =>
1371                               $primary_cust_svc
1372                                 ? { $primary_cust_svc->hash,
1373                                     label => [ $primary_cust_svc->label ],
1374                                     finger => $primary_cust_svc->svc_x->finger, #uuh
1375                                     $primary_cust_svc->part_svc->hash,
1376                                   }
1377                                 : {}, #'' ?
1378                           };
1379                         } $cust_main->ncancelled_pkgs
1380                   ],
1381     'small_custview' =>
1382       small_custview( $cust_main, $conf->config('countrydefault') ),
1383   };
1384
1385 }
1386
1387 sub list_svcs {
1388   my $p = shift;
1389
1390   my($context, $session, $custnum) = _custoragent_session_custnum($p);
1391   return { 'error' => $session } if $context eq 'error';
1392
1393   my $search = { 'custnum' => $custnum };
1394   $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
1395   my $cust_main = qsearchs('cust_main', $search )
1396     or return { 'error' => "unknown custnum $custnum" };
1397
1398   my $pkgnum = $session->{'pkgnum'} || $p->{'pkgnum'} || '';
1399   if ( ! $pkgnum && $p->{'svcnum'} ) {
1400     my $cust_svc = qsearchs('cust_svc', { 'svcnum' => $p->{'svcnum'} } );
1401     $pkgnum = $cust_svc->pkgnum if $cust_svc;
1402   }
1403
1404   my @cust_svc = ();
1405   #foreach my $cust_pkg ( $cust_main->ncancelled_pkgs ) {
1406   foreach my $cust_pkg ( $p->{'ncancelled'} 
1407                          ? $cust_main->ncancelled_pkgs
1408                          : $cust_main->unsuspended_pkgs ) {
1409     next if $pkgnum && $cust_pkg->pkgnum != $pkgnum;
1410     push @cust_svc, @{[ $cust_pkg->cust_svc ]}; #@{[ ]} to force array context
1411   }
1412   if ( $p->{'svcdb'} ) {
1413     my $svcdb = ref($p->{'svcdb'}) eq 'HASH'
1414                   ? $p->{'svcdb'}
1415                   : ref($p->{'svcdb'}) eq 'ARRAY'
1416                     ? { map { $_=>1 } @{ $p->{'svcdb'} } }
1417                     : { $p->{'svcdb'} => 1 };
1418     @cust_svc = grep $svcdb->{ $_->part_svc->svcdb }, @cust_svc
1419   }
1420
1421   #@svc_x = sort { $a->domain cmp $b->domain || $a->username cmp $b->username }
1422   #              @svc_x;
1423
1424     my $conf = new FS::Conf;
1425
1426   { 
1427     'svcnum'   => $session->{'svcnum'},
1428     'custnum'  => $custnum,
1429     'date_format' => $conf->config('date_format') || '%m/%d/%Y',
1430     'view_usage_nodomain' => $conf->exists('selfservice-view_usage_nodomain'),
1431     'svcs'     => [
1432       map { 
1433             my $svc_x = $_->svc_x;
1434             my($label, $value) = $_->label;
1435             my $svcdb = $_->part_svc->svcdb;
1436             my $part_pkg = $_->cust_pkg->part_pkg;
1437
1438             my %hash = (
1439               'svcnum' => $_->svcnum,
1440               'svcdb'  => $svcdb,
1441               'label'  => $label,
1442               'value'  => $value,
1443             );
1444
1445             if ( $svcdb eq 'svc_acct' ) {
1446               %hash = (
1447                 %hash,
1448                 'username'   => $svc_x->username,
1449                 'email'      => $svc_x->email,
1450                 'finger'     => $svc_x->finger,
1451                 'seconds'    => $svc_x->seconds,
1452                 'upbytes'    => display_bytecount($svc_x->upbytes),
1453                 'downbytes'  => display_bytecount($svc_x->downbytes),
1454                 'totalbytes' => display_bytecount($svc_x->totalbytes),
1455
1456                 'recharge_amount'  => $part_pkg->option('recharge_amount',1),
1457                 'recharge_seconds' => $part_pkg->option('recharge_seconds',1),
1458                 'recharge_upbytes'    =>
1459                   display_bytecount($part_pkg->option('recharge_upbytes',1)),
1460                 'recharge_downbytes'  =>
1461                   display_bytecount($part_pkg->option('recharge_downbytes',1)),
1462                 'recharge_totalbytes' =>
1463                   display_bytecount($part_pkg->option('recharge_totalbytes',1)),
1464                 # more...
1465               );
1466
1467             } elsif ( $svcdb eq 'svc_dsl' ) {
1468               $hash{'phonenum'} = $svc_x->phonenum;
1469               if ( $svc_x->first || $svc_x->get('last') || $svc_x->company ) {
1470                 $hash{'name'} = $svc_x->first. ' '. $svc_x->get('last');
1471                 $hash{'name'} = $svc_x->company. ' ('. $hash{'name'}. ')'
1472                   if $svc_x->company;
1473               } else {
1474                 $hash{'name'} = $cust_main->name;
1475               }
1476             }
1477             # elsif ( $svcdb eq 'svc_phone' || $svcdb eq 'svc_port' ) {
1478             #  %hash = (
1479             #    %hash,
1480             #  );
1481             #}
1482
1483             \%hash;
1484           }
1485           @cust_svc
1486     ],
1487   };
1488
1489 }
1490
1491 sub _customer_svc_x {
1492   my($custnum, $svcnum, $table) = @_;
1493
1494   $custnum =~ /^(\d+)$/ or die "illegal custnum";
1495   my $search = " AND custnum = $1";
1496   #$search .= " AND agentnum = ". $session->{'agentnum'} if $context eq 'agent';
1497
1498   qsearchs( {
1499     'table'     => ($table || 'svc_acct'),
1500     'addl_from' => 'LEFT JOIN cust_svc  USING ( svcnum  ) '.
1501                    'LEFT JOIN cust_pkg  USING ( pkgnum  ) ',#.
1502                    #'LEFT JOIN cust_main USING ( custnum ) ',
1503     'hashref'   => { 'svcnum' => $svcnum, },
1504     'extra_sql' => $search, #important
1505   } );
1506
1507 }
1508
1509 sub list_dsl_devices {
1510   my $p = shift;
1511
1512   my($context, $session, $custnum) = _custoragent_session_custnum($p);
1513   return { 'error' => $session } if $context eq 'error';
1514
1515   my $svc_dsl = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_dsl' )
1516     or return { 'error' => "Service not found" };
1517
1518   return {
1519     'devices' => [ map {
1520                          +{ 'mac_addr' => $_->mac_addr };
1521                        } $svc_dsl->dsl_device
1522                  ],
1523   };
1524
1525 }
1526
1527 sub add_dsl_device {
1528   my $p = shift;
1529
1530   my($context, $session, $custnum) = _custoragent_session_custnum($p);
1531   return { 'error' => $session } if $context eq 'error';
1532
1533   my $svc_dsl = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_dsl' )
1534     or return { 'error' => "Service not found" };
1535
1536   return { 'error' => 'No MAC address supplied' }
1537     unless length($p->{'mac_addr'});
1538
1539   my $dsl_device = new FS::dsl_device { 'svcnum'   => $svc_dsl->svcnum,
1540                                         'mac_addr' => scalar($p->{'mac_addr'}),
1541                                       };
1542   my $error = $dsl_device->insert;
1543   return { 'error' => $error };
1544
1545 }
1546
1547 sub delete_dsl_device {
1548   my $p = shift;
1549
1550   my($context, $session, $custnum) = _custoragent_session_custnum($p);
1551   return { 'error' => $session } if $context eq 'error';
1552
1553   my $svc_dsl = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_dsl' )
1554     or return { 'error' => "Service not found" };
1555
1556   my $dsl_device = qsearchs('dsl_device', { 'svcnum'   => $svc_dsl->svcnum,
1557                                             'mac_addr' => scalar($p->{'mac_addr'}),
1558                                           }
1559                            )
1560     or return { 'error' => 'Unknown MAC address: '. $p->{'mac_addr'} };
1561
1562   my $error = $dsl_device->delete;
1563   return { 'error' => $error };
1564
1565 }
1566
1567 sub port_graph {
1568   my $p = shift;
1569   _usage_details( \&_port_graph, $p,
1570                   'svcdb' => 'svc_port',
1571                 );
1572 }
1573
1574 sub _port_graph {
1575   my($svc_port, $begin, $end) = @_;
1576   my @usage = ();
1577   my $pngOrError = $svc_port->graph_png( start=>$begin, end=> $end );
1578   push @usage, { 'png' => $pngOrError };
1579   (@usage);
1580 }
1581
1582 sub _list_svc_usage {
1583   my($svc_acct, $begin, $end) = @_;
1584   my @usage = ();
1585   foreach my $part_export ( 
1586     map { qsearch ( 'part_export', { 'exporttype' => $_ } ) }
1587     qw( sqlradius sqlradius_withdomain )
1588   ) {
1589     push @usage, @ { $part_export->usage_sessions($begin, $end, $svc_acct) };
1590   }
1591   (@usage);
1592 }
1593
1594 sub list_svc_usage {
1595   _usage_details(\&_list_svc_usage, @_);
1596 }
1597
1598 sub _list_support_usage {
1599   my($svc_acct, $begin, $end) = @_;
1600   my @usage = ();
1601   foreach ( grep { $begin <= $_->_date && $_->_date <= $end }
1602             qsearch('acct_rt_transaction', { 'svcnum' => $svc_acct->svcnum })
1603           ) {
1604     push @usage, { 'seconds'  => $_->seconds,
1605                    'support'  => $_->support,
1606                    '_date'    => $_->_date,
1607                    'id'       => $_->transaction_id,
1608                    'creator'  => $_->creator,
1609                    'subject'  => $_->subject,
1610                    'status'   => $_->status,
1611                    'ticketid' => $_->ticketid,
1612                  };
1613   }
1614   (@usage);
1615 }
1616
1617 sub list_support_usage {
1618   _usage_details(\&_list_support_usage, @_);
1619 }
1620
1621 sub _list_cdr_usage {
1622   my($svc_phone, $begin, $end) = @_;
1623   map [ $_->downstream_csv('format' => 'default', 'keeparray' => 1) ], #XXX config for format
1624                        $svc_phone->get_cdrs( 'begin'=>$begin, 'end'=>$end, );
1625 }
1626
1627 sub list_cdr_usage {
1628   my $p = shift;
1629   _usage_details( \&_list_cdr_usage, $p,
1630                   'svcdb' => 'svc_phone',
1631                 );
1632 }
1633
1634 sub _usage_details {
1635   my($callback, $p, %opt) = @_;
1636
1637   my($context, $session, $custnum) = _custoragent_session_custnum($p);
1638   return { 'error' => $session } if $context eq 'error';
1639
1640   my $search = { 'svcnum' => $p->{'svcnum'} };
1641   $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
1642
1643   my $svcdb = $opt{'svcdb'} || 'svc_acct';
1644
1645   my $svc_x = qsearchs( $svcdb, $search );
1646   return { 'error' => 'No service selected in list_svc_usage' } 
1647     unless $svc_x;
1648
1649   my $header = $svcdb eq 'svc_phone'
1650                  ? [ split(',', FS::cdr::invoice_header('default') ) ]  #XXX
1651                  : [];
1652
1653   my $cust_pkg = $svc_x->cust_svc->cust_pkg;
1654   my $freq     = $cust_pkg->part_pkg->freq;
1655   my $start    = $cust_pkg->setup;
1656   #my $end      = $cust_pkg->bill; # or time?
1657   my $end      = time;
1658
1659   unless ( $p->{beginning} ) {
1660     $p->{beginning} = $cust_pkg->last_bill;
1661     $p->{ending}    = $end;
1662   }
1663
1664   my (@usage) = &$callback($svc_x, $p->{beginning}, $p->{ending});
1665
1666   #kinda false laziness with FS::cust_main::bill, but perhaps
1667   #we should really change this bit to DateTime and DateTime::Duration
1668   #
1669   #change this bit to use Date::Manip? CAREFUL with timezones (see
1670   # mailing list archive)
1671   my ($nsec,$nmin,$nhour,$nmday,$nmon,$nyear) =
1672     (localtime($p->{ending}) )[0,1,2,3,4,5];
1673   my ($psec,$pmin,$phour,$pmday,$pmon,$pyear) =
1674     (localtime($p->{beginning}) )[0,1,2,3,4,5];
1675
1676   if ( $freq =~ /^\d+$/ ) {
1677     $nmon += $freq;
1678     until ( $nmon < 12 ) { $nmon -= 12; $nyear++; }
1679     $pmon -= $freq;
1680     until ( $pmon >= 0 ) { $pmon += 12; $pyear--; }
1681   } elsif ( $freq =~ /^(\d+)w$/ ) {
1682     my $weeks = $1;
1683     $nmday += $weeks * 7;
1684     $pmday -= $weeks * 7;
1685   } elsif ( $freq =~ /^(\d+)d$/ ) {
1686     my $days = $1;
1687     $nmday += $days;
1688     $pmday -= $days;
1689   } elsif ( $freq =~ /^(\d+)h$/ ) {
1690     my $hours = $1;
1691     $nhour += $hours;
1692     $phour -= $hours;
1693   } else {
1694     return { 'error' => "unparsable frequency: ". $freq };
1695   }
1696   
1697   my $previous  = timelocal_nocheck($psec,$pmin,$phour,$pmday,$pmon,$pyear);
1698   my $next      = timelocal_nocheck($nsec,$nmin,$nhour,$nmday,$nmon,$nyear);
1699
1700   { 
1701     'error'     => '',
1702     'svcnum'    => $p->{svcnum},
1703     'beginning' => $p->{beginning},
1704     'ending'    => $p->{ending},
1705     'previous'  => ($previous > $start) ? $previous : $start,
1706     'next'      => ($next < $end) ? $next : $end,
1707     'header'    => $header,
1708     'usage'     => \@usage,
1709   };
1710 }
1711
1712 sub order_pkg {
1713   my $p = shift;
1714
1715   my($context, $session, $custnum) = _custoragent_session_custnum($p);
1716   return { 'error' => $session } if $context eq 'error';
1717
1718   my $search = { 'custnum' => $custnum };
1719   $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
1720   my $cust_main = qsearchs('cust_main', $search )
1721     or return { 'error' => "unknown custnum $custnum" };
1722
1723   my $status = $cust_main->status;
1724   #false laziness w/ClientAPI/Signup.pm
1725
1726   my $cust_pkg = new FS::cust_pkg ( {
1727     'custnum' => $custnum,
1728     'pkgpart' => $p->{'pkgpart'},
1729   } );
1730   my $error = $cust_pkg->check;
1731   return { 'error' => $error } if $error;
1732
1733   my @svc = ();
1734   unless ( $p->{'svcpart'} eq 'none' ) {
1735
1736     my $svcdb;
1737     my $svcpart = '';
1738     if ( $p->{'svcpart'} =~ /^(\d+)$/ ) {
1739       $svcpart = $1;
1740       my $part_svc = qsearchs('part_svc', { 'svcpart' => $svcpart } );
1741       return { 'error' => "Unknown svcpart $svcpart" } unless $part_svc;
1742       $svcdb = $part_svc->svcdb;
1743     } else {
1744       $svcdb = 'svc_acct';
1745     }
1746     $svcpart ||= $cust_pkg->part_pkg->svcpart($svcdb);
1747
1748     my %fields = (
1749       'svc_acct'     => [ qw( username domsvc _password sec_phrase popnum ) ],
1750       'svc_domain'   => [ qw( domain ) ],
1751       'svc_phone'    => [ qw( phonenum pin sip_password phone_name ) ],
1752       'svc_external' => [ qw( id title ) ],
1753       'svc_pbx'      => [ qw( id title ) ],
1754     );
1755   
1756     my $svc_x = "FS::$svcdb"->new( {
1757       'svcpart'   => $svcpart,
1758       map { $_ => $p->{$_} } @{$fields{$svcdb}}
1759     } );
1760     
1761     if ( $svcdb eq 'svc_acct' && exists($p->{"snarf_machine1"}) ) {
1762       my @acct_snarf;
1763       my $snarfnum = 1;
1764       while ( length($p->{"snarf_machine$snarfnum"}) ) {
1765         my $acct_snarf = new FS::acct_snarf ( {
1766           'machine'   => $p->{"snarf_machine$snarfnum"},
1767           'protocol'  => $p->{"snarf_protocol$snarfnum"},
1768           'username'  => $p->{"snarf_username$snarfnum"},
1769           '_password' => $p->{"snarf_password$snarfnum"},
1770         } );
1771         $snarfnum++;
1772         push @acct_snarf, $acct_snarf;
1773       }
1774       $svc_x->child_objects( \@acct_snarf );
1775     }
1776     
1777     my $y = $svc_x->setdefault; # arguably should be in new method
1778     return { 'error' => $y } if $y && !ref($y);
1779   
1780     $error = $svc_x->check;
1781     return { 'error' => $error } if $error;
1782
1783     push @svc, $svc_x;
1784
1785   }
1786
1787   use Tie::RefHash;
1788   tie my %hash, 'Tie::RefHash';
1789   %hash = ( $cust_pkg => \@svc );
1790   #msgcat
1791   $error = $cust_main->order_pkgs( \%hash, 'noexport' => 1 );
1792   return { 'error' => $error } if $error;
1793
1794   my $conf = new FS::Conf;
1795   if ( $conf->exists('signup_server-realtime') ) {
1796
1797     my $bill_error = _do_bop_realtime( $cust_main, $status );
1798
1799     if ($bill_error) {
1800       $cust_pkg->cancel('quiet'=>1);
1801       return $bill_error;
1802     } else {
1803       $cust_pkg->reexport;
1804     }
1805
1806   } else {
1807     $cust_pkg->reexport;
1808   }
1809
1810   my $svcnum = $svc[0] ? $svc[0]->svcnum : '';
1811
1812   return { error=>'', pkgnum=>$cust_pkg->pkgnum, svcnum=>$svcnum };
1813
1814 }
1815
1816 sub change_pkg {
1817   my $p = shift;
1818
1819   my($context, $session, $custnum) = _custoragent_session_custnum($p);
1820   return { 'error' => $session } if $context eq 'error';
1821
1822   my $search = { 'custnum' => $custnum };
1823   $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
1824   my $cust_main = qsearchs('cust_main', $search )
1825     or return { 'error' => "unknown custnum $custnum" };
1826
1827   my $status = $cust_main->status;
1828   my $cust_pkg = qsearchs('cust_pkg', { 'pkgnum' => $p->{pkgnum} } )
1829     or return { 'error' => "unknown package $p->{pkgnum}" };
1830
1831   my @newpkg;
1832   my $error = FS::cust_pkg::order( $custnum,
1833                                    [$p->{pkgpart}],
1834                                    [$p->{pkgnum}],
1835                                    \@newpkg,
1836                                  );
1837
1838   my $conf = new FS::Conf;
1839   if ( $conf->exists('signup_server-realtime') ) {
1840
1841     my $bill_error = _do_bop_realtime( $cust_main, $status );
1842
1843     if ($bill_error) {
1844       $newpkg[0]->suspend;
1845       return $bill_error;
1846     } else {
1847       $newpkg[0]->reexport;
1848     }
1849
1850   } else {  
1851     $newpkg[0]->reexport;
1852   }
1853
1854   return { error => '', pkgnum => $cust_pkg->pkgnum };
1855
1856 }
1857
1858 sub order_recharge {
1859   my $p = shift;
1860
1861   my($context, $session, $custnum) = _custoragent_session_custnum($p);
1862   return { 'error' => $session } if $context eq 'error';
1863
1864   my $search = { 'custnum' => $custnum };
1865   $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
1866   my $cust_main = qsearchs('cust_main', $search )
1867     or return { 'error' => "unknown custnum $custnum" };
1868
1869   my $status = $cust_main->status;
1870   my $cust_svc = qsearchs( 'cust_svc', { 'svcnum' => $p->{'svcnum'} } )
1871     or return { 'error' => "unknown service " . $p->{'svcnum'} };
1872
1873   my $svc_x = $cust_svc->svc_x;
1874   my $part_pkg = $cust_svc->cust_pkg->part_pkg;
1875
1876   my %vhash =
1877     map { $_ =~ /^recharge_(.*)$/; $1, $part_pkg->option($_, 1) } 
1878     qw ( recharge_seconds recharge_upbytes recharge_downbytes
1879          recharge_totalbytes );
1880   my $amount = $part_pkg->option('recharge_amount', 1); 
1881   
1882   my ($l, $v, $d) = $cust_svc->label;  # blah
1883   my $pkg = "Recharge $v"; 
1884
1885   my $bill_error = $cust_main->charge($amount, $pkg,
1886      "time: $vhash{seconds}, up: $vhash{upbytes}," . 
1887      "down: $vhash{downbytes}, total: $vhash{totalbytes}",
1888      $part_pkg->taxclass); #meh
1889
1890   my $conf = new FS::Conf;
1891   if ( $conf->exists('signup_server-realtime') && !$bill_error ) {
1892
1893     $bill_error = _do_bop_realtime( $cust_main, $status );
1894
1895     if ($bill_error) {
1896       return $bill_error;
1897     } else {
1898       my $error = $svc_x->recharge (\%vhash);
1899       return { 'error' => $error } if $error;
1900     }
1901
1902   } else {  
1903     my $error = $bill_error;
1904     $error ||= $svc_x->recharge (\%vhash);
1905     return { 'error' => $error } if $error;
1906   }
1907
1908   return { error => '', svc => $cust_svc->part_svc->svc };
1909
1910 }
1911
1912 sub _do_bop_realtime {
1913   my ($cust_main, $status) = (shift, shift);
1914
1915     my $old_balance = $cust_main->balance;
1916
1917     my $bill_error =    $cust_main->bill
1918                      || $cust_main->apply_payments_and_credits
1919                      || $cust_main->realtime_collect('selfservice' => 1);
1920
1921     if (    $cust_main->balance > $old_balance
1922          && $cust_main->balance > 0
1923          && ( $cust_main->payby !~ /^(BILL|DCRD|DCHK)$/ ?
1924               1 : $status eq 'suspended' ) ) {
1925       #this makes sense.  credit is "un-doing" the invoice
1926       my $conf = new FS::Conf;
1927       $cust_main->credit( sprintf("%.2f", $cust_main->balance - $old_balance ),
1928                           'self-service decline',
1929                           'reason_type' => $conf->config('signup_credit_type'),
1930                         );
1931       $cust_main->apply_credits( 'order' => 'newest' );
1932
1933       return { 'error' => '_decline', 'bill_error' => $bill_error };
1934     }
1935
1936     '';
1937 }
1938
1939 sub renew_info {
1940   my $p = shift;
1941
1942   my($context, $session, $custnum) = _custoragent_session_custnum($p);
1943   return { 'error' => $session } if $context eq 'error';
1944
1945   my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1946     or return { 'error' => "unknown custnum $custnum" };
1947
1948   my @cust_pkg = sort { $a->bill <=> $b->bill }
1949                  grep { $_->part_pkg->freq ne '0' }
1950                  $cust_main->ncancelled_pkgs;
1951
1952   #return { 'error' => 'No active packages to renew.' } unless @cust_pkg;
1953
1954   my $total = $cust_main->balance;
1955
1956   my @array = map {
1957                     my $bill = $_->bill;
1958                     $total += $_->part_pkg->base_recur($_, \$bill);
1959                     my $renew_date = $_->part_pkg->add_freq($_->bill);
1960                     {
1961                       'pkgnum'             => $_->pkgnum,
1962                       'amount'             => sprintf('%.2f', $total),
1963                       'bill_date'          => $_->bill,
1964                       'bill_date_pretty'   => time2str('%x', $_->bill),
1965                       'renew_date'         => $renew_date,
1966                       'renew_date_pretty'  => time2str('%x', $renew_date),
1967                       'expire_date'        => $_->expire,
1968                       'expire_date_pretty' => time2str('%x', $_->expire),
1969                     };
1970                   }
1971                   @cust_pkg;
1972
1973   return { 'dates' => \@array };
1974
1975 }
1976
1977 sub payment_info_renew_info {
1978   my $p = shift;
1979   my $renew_info   = renew_info($p);
1980   my $payment_info = payment_info($p);
1981   return { %$renew_info,
1982            %$payment_info,
1983          };
1984 }
1985
1986 sub order_renew {
1987   my $p = shift;
1988
1989   my($context, $session, $custnum) = _custoragent_session_custnum($p);
1990   return { 'error' => $session } if $context eq 'error';
1991
1992   my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1993     or return { 'error' => "unknown custnum $custnum" };
1994
1995   my $date = $p->{'date'};
1996
1997   my $now = time;
1998
1999   #freeside-daily -n -d $date fs_daily $custnum
2000   $cust_main->bill_and_collect( 'time'         => $date,
2001                                 'invoice_time' => $now,
2002                                 'actual_time'  => $now,
2003                                 'check_freq'   => '1d',
2004                               );
2005
2006   return { 'error' => '' };
2007
2008 }
2009
2010 sub suspend_pkg {
2011   my $p = shift;
2012   my $session = _cache->get($p->{'session_id'})
2013     or return { 'error' => "Can't resume session" }; #better error message
2014
2015   my $custnum = $session->{'custnum'};
2016
2017   my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
2018     or return { 'error' => "unknown custnum $custnum" };
2019
2020   my $conf = new FS::Conf;
2021   my $reasonnum = 
2022     $conf->config('selfservice-self_suspend_reason', $cust_main->agentnum)
2023       or return { 'error' => 'Permission denied' };
2024
2025   my $pkgnum = $p->{'pkgnum'};
2026
2027   my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
2028                                         'pkgnum'  => $pkgnum,   } )
2029     or return { 'error' => "unknown pkgnum $pkgnum" };
2030
2031   my $error = $cust_pkg->suspend(reason => $reasonnum);
2032   return { 'error' => $error };
2033
2034 }
2035
2036 sub cancel_pkg {
2037   my $p = shift;
2038   my $session = _cache->get($p->{'session_id'})
2039     or return { 'error' => "Can't resume session" }; #better error message
2040
2041   my $custnum = $session->{'custnum'};
2042
2043   my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
2044     or return { 'error' => "unknown custnum $custnum" };
2045
2046   my $pkgnum = $p->{'pkgnum'};
2047
2048   my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
2049                                         'pkgnum'  => $pkgnum,   } )
2050     or return { 'error' => "unknown pkgnum $pkgnum" };
2051
2052   my $error = $cust_pkg->cancel('quiet' => 1);
2053   return { 'error' => $error };
2054
2055 }
2056
2057 sub provision_phone {
2058  my $p = shift;
2059  my @bulkdid;
2060  @bulkdid = @{$p->{'bulkdid'}} if $p->{'bulkdid'};
2061
2062  if($p->{'svcnum'} && $p->{'svcnum'} =~ /^\d+$/){
2063       my($context, $session, $custnum) = _custoragent_session_custnum($p);
2064       return { 'error' => $session } if $context eq 'error';
2065     
2066       my $svc_phone = qsearchs('svc_phone', { svcnum => $p->{'svcnum'} });
2067       return { 'error' => 'service not found' } unless $svc_phone;
2068       return { 'error' => 'invalid svcnum' } 
2069         if $svc_phone && $svc_phone->cust_svc->cust_pkg->custnum != $custnum;
2070
2071       $svc_phone->email($p->{'email'}) 
2072         if $svc_phone->email ne $p->{'email'} && $p->{'email'} =~ /^([\w\.\d@]+|)$/;
2073       $svc_phone->forwarddst($p->{'forwarddst'}) 
2074         if $svc_phone->forwarddst ne $p->{'forwarddst'} 
2075             && $p->{'forwarddst'} =~ /^(\d+|)$/;
2076       return { 'error' => $svc_phone->replace };
2077  }
2078
2079 # single DID LNP
2080  unless($p->{'lnp'}) {
2081     $p->{'lnp_desired_due_date'} = parse_datetime($p->{'lnp_desired_due_date'});
2082     $p->{'lnp_status'} = "portingin";
2083     return _provision( 'FS::svc_phone',
2084                   [qw(lnp_desired_due_date lnp_other_provider 
2085                     lnp_other_provider_account phonenum countrycode lnp_status)],
2086                   [qw(phonenum countrycode)],
2087                   $p,
2088                   @_
2089                 );
2090  }
2091
2092 # single DID order
2093  unless (scalar(@bulkdid)) {
2094     return _provision( 'FS::svc_phone',
2095                   [qw(phonenum countrycode)],
2096                   [qw(phonenum countrycode)],
2097                   $p,
2098                   @_
2099                 );
2100  }
2101
2102 # bulk DID order case
2103   my $error;
2104   foreach my $did ( @bulkdid ) {
2105     $did =~ s/[^0-9]//g;
2106     $error = _provision( 'FS::svc_phone',
2107               [qw(phonenum countrycode)],
2108               [qw(phonenum countrycode)],
2109               {
2110                 'pkgnum' => $p->{'pkgnum'},
2111                 'svcpart' => $p->{'svcpart'},
2112                 'phonenum' => $did,
2113                 'countrycode' => $p->{'countrycode'},
2114                 'session_id' => $p->{'session_id'},
2115               }
2116             );
2117     return $error if ($error->{'error'} && length($error->{'error'}) > 1);
2118   }
2119   { 'bulkdid' => [ @bulkdid ], 'svc' => $error->{'svc'} }
2120 }
2121
2122 sub provision_acct {
2123   my $p = shift;
2124   warn "provision_acct called\n"
2125     if $DEBUG;
2126
2127   return { 'error' => gettext('passwords_dont_match') }
2128     if $p->{'_password'} ne $p->{'_password2'};
2129   return { 'error' => gettext('empty_password') }
2130     unless length($p->{'_password'});
2131  
2132   if ($p->{'domsvc'}) {
2133     my %domains = domain_select_hash FS::svc_acct(map { $_ => $p->{$_} }
2134                                                   qw ( svcpart pkgnum ) );
2135     return { 'error' => gettext('invalid_domain') }
2136       unless ($domains{$p->{'domsvc'}});
2137   }
2138
2139   warn "provision_acct calling _provision\n"
2140     if $DEBUG;
2141   _provision( 'FS::svc_acct',
2142               [qw(username _password domsvc)],
2143               [qw(username _password domsvc)],
2144               $p,
2145               @_
2146             );
2147 }
2148
2149 sub provision_external {
2150   my $p = shift;
2151   #_provision( 'FS::svc_external', [qw(id title)], [qw(id title)], $p, @_ );
2152   _provision( 'FS::svc_external',
2153               [],
2154               [qw(id title)],
2155               $p,
2156               @_
2157             );
2158 }
2159
2160 sub _provision {
2161   my( $class, $fields, $return_fields, $p ) = splice(@_, 0, 4);
2162   warn "_provision called for $class\n"
2163     if $DEBUG;
2164
2165   my($context, $session, $custnum) = _custoragent_session_custnum($p);
2166   return { 'error' => $session } if $context eq 'error';
2167
2168   my $search = { 'custnum' => $custnum };
2169   $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2170   my $cust_main = qsearchs('cust_main', $search )
2171     or return { 'error' => "unknown custnum $custnum" };
2172
2173   my $pkgnum = $p->{'pkgnum'};
2174
2175   warn "searching for custnum $custnum pkgnum $pkgnum\n"
2176     if $DEBUG;
2177   my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
2178                                         'pkgnum'  => $pkgnum,
2179                                                                } )
2180     or return { 'error' => "unknown pkgnum $pkgnum" };
2181
2182   warn "searching for svcpart ". $p->{'svcpart'}. "\n"
2183     if $DEBUG;
2184   my $part_svc = qsearchs('part_svc', { 'svcpart' => $p->{'svcpart'} } )
2185     or return { 'error' => "unknown svcpart $p->{'svcpart'}" };
2186
2187   warn "creating $class record\n"
2188     if $DEBUG;
2189   my $svc_x = $class->new( {
2190     'pkgnum'  => $p->{'pkgnum'},
2191     'svcpart' => $p->{'svcpart'},
2192     map { $_ => $p->{$_} } @$fields
2193   } );
2194   warn "inserting $class record\n"
2195     if $DEBUG;
2196   my $error = $svc_x->insert;
2197
2198   unless ( $error ) {
2199     warn "finding inserted record for svcnum ". $svc_x->svcnum. "\n"
2200       if $DEBUG;
2201     $svc_x = qsearchs($svc_x->table, { 'svcnum' => $svc_x->svcnum })
2202   }
2203
2204   my $return = { 'svc'   => $part_svc->svc,
2205                  'error' => $error,
2206                  map { $_ => $svc_x->get($_) } @$return_fields
2207                };
2208   warn "_provision returning ". Dumper($return). "\n"
2209     if $DEBUG;
2210   return $return;
2211
2212 }
2213
2214 sub part_svc_info {
2215   my $p = shift;
2216
2217   my($context, $session, $custnum) = _custoragent_session_custnum($p);
2218   return { 'error' => $session } if $context eq 'error';
2219
2220   my $search = { 'custnum' => $custnum };
2221   $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2222   my $cust_main = qsearchs('cust_main', $search )
2223     or return { 'error' => "unknown custnum $custnum" };
2224
2225   my $pkgnum = $p->{'pkgnum'};
2226
2227   my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
2228                                         'pkgnum'  => $pkgnum,
2229                                                                } )
2230     or return { 'error' => "unknown pkgnum $pkgnum" };
2231
2232   my $svcpart = $p->{'svcpart'};
2233
2234   my $pkg_svc = qsearchs('pkg_svc', { 'pkgpart' => $cust_pkg->pkgpart,
2235                                       'svcpart' => $svcpart,           } )
2236     or return { 'error' => "unknown svcpart $svcpart for pkgnum $pkgnum" };
2237   my $part_svc = $pkg_svc->part_svc;
2238
2239   my $conf = new FS::Conf;
2240
2241   my $ret = {
2242     'svc'     => $part_svc->svc,
2243     'svcdb'   => $part_svc->svcdb,
2244     'pkgnum'  => $pkgnum,
2245     'svcpart' => $svcpart,
2246     'custnum' => $custnum,
2247
2248     'security_phrase' => 0, #XXX !
2249     'svc_acct_pop'    => [], #XXX !
2250     'popnum'          => '',
2251     'init_popstate'   => '',
2252     'popac'           => '',
2253     'acstate'         => '',
2254
2255     'small_custview' =>
2256       small_custview( $cust_main, $conf->config('countrydefault') ),
2257
2258   };
2259
2260   if ($p->{'svcnum'} && $p->{'svcnum'} =~ /^\d+$/ 
2261                      && $ret->{'svcdb'} eq 'svc_phone') {
2262         $ret->{'svcnum'} = $p->{'svcnum'};
2263         my $svc_phone = qsearchs('svc_phone', { svcnum => $p->{'svcnum'} });
2264         if ( $svc_phone && $svc_phone->cust_svc->cust_pkg->custnum == $custnum ) {
2265             $ret->{'email'} = $svc_phone->email;
2266             $ret->{'forwarddst'} = $svc_phone->forwarddst;
2267         }
2268   }
2269
2270   $ret;
2271 }
2272
2273 sub unprovision_svc {
2274   my $p = shift;
2275
2276   my($context, $session, $custnum) = _custoragent_session_custnum($p);
2277   return { 'error' => $session } if $context eq 'error';
2278
2279   my $search = { 'custnum' => $custnum };
2280   $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2281   my $cust_main = qsearchs('cust_main', $search )
2282     or return { 'error' => "unknown custnum $custnum" };
2283
2284   my $svcnum = $p->{'svcnum'};
2285
2286   my $cust_svc = qsearchs('cust_svc', { 'svcnum'  => $svcnum, } )
2287     or return { 'error' => "unknown svcnum $svcnum" };
2288
2289   return { 'error' => "Service $svcnum does not belong to customer $custnum" }
2290     unless $cust_svc->cust_pkg->custnum == $custnum;
2291
2292   my $conf = new FS::Conf;
2293
2294   return { 'svc'   => $cust_svc->part_svc->svc,
2295            'error' => $cust_svc->cancel,
2296            'small_custview' =>
2297              small_custview( $cust_main, $conf->config('countrydefault') ),
2298          };
2299
2300 }
2301
2302 sub myaccount_passwd {
2303   my $p = shift;
2304   my($context, $session, $custnum) = _custoragent_session_custnum($p);
2305   return { 'error' => $session } if $context eq 'error';
2306
2307   return { 'error' => "New passwords don't match." }
2308     if $p->{'new_password'} ne $p->{'new_password2'};
2309
2310   return { 'error' => 'Enter new password' }
2311     unless length($p->{'new_password'});
2312
2313   #my $search = { 'custnum' => $custnum };
2314   #$search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2315   $custnum =~ /^(\d+)$/ or die "illegal custnum";
2316   my $search = " AND custnum = $1";
2317   $search .= " AND agentnum = ". $session->{'agentnum'} if $context eq 'agent';
2318
2319   my $svc_acct = qsearchs( {
2320     'table'     => 'svc_acct',
2321     'addl_from' => 'LEFT JOIN cust_svc  USING ( svcnum  ) '.
2322                    'LEFT JOIN cust_pkg  USING ( pkgnum  ) '.
2323                    'LEFT JOIN cust_main USING ( custnum ) ',
2324     'hashref'   => { 'svcnum' => $p->{'svcnum'}, },
2325     'extra_sql' => $search, #important
2326   } )
2327     or return { 'error' => "Service not found" };
2328
2329   if ( exists($p->{'old_password'}) ) {
2330     return { 'error' => "Incorrect password." }
2331       unless $svc_acct->check_password($p->{'old_password'});
2332   }
2333
2334   $svc_acct->_password($p->{'new_password'});
2335   my $error = $svc_acct->replace();
2336
2337   my($label, $value) = $svc_acct->cust_svc->label;
2338
2339   return { 'error' => $error,
2340            'label' => $label,
2341            'value' => $value,
2342          };
2343
2344 }
2345
2346 sub reset_passwd {
2347   my $p = shift;
2348
2349   my $conf = new FS::Conf;
2350   my $verification = $conf->config('selfservice-password_reset_verification')
2351     or return { 'error' => 'Password resets disabled' };
2352
2353   my $username = $p->{'username'};
2354
2355   my $svc_domain = qsearchs('svc_domain', { 'domain' => $p->{'domain'} } )
2356     or return { 'error' => 'Account not found' };
2357
2358   my $svc_acct = qsearchs('svc_acct', { 'username' => $p->{'username'},
2359                                         'domsvc'   => $svc_domain->svcnum  }
2360                          )
2361     or return { 'error' => 'Account not found' };
2362
2363   my $cust_pkg = $svc_acct->cust_svc->cust_pkg
2364     or return { 'error' => 'Account not found' };
2365
2366   my $cust_main = $cust_pkg->cust_main;
2367
2368   my %verify = (
2369     'paymask' => sub { 
2370       my( $p, $cust_main ) = @_;
2371       $cust_main->payby =~ /^(CARD|DCRD|CHEK|DCHK)$/
2372         && $p->{'paymask'} eq substr($cust_main->paymask, -4)
2373     },
2374     'amount'  => sub {
2375       my( $p, $cust_main ) = @_;
2376       my $cust_pay = qsearchs({
2377         'table' => 'cust_pay',
2378         'hashref' => { 'custnum' => $cust_main->custnum },
2379         'order_by' => 'ORDER BY _date DESC LIMIT 1',
2380       })
2381         or return 0;
2382
2383       $p->{'amount'} == $cust_pay->paid;
2384     },
2385     'zip'     => sub {
2386       my( $p, $cust_main ) = @_;
2387       $p->{'zip'} eq $cust_main->zip
2388         || ( $cust_main->ship_zip && $p->{'zip'} eq $cust_main->ship_zip );
2389     },
2390   );
2391
2392   foreach my $verify ( split(',', $verification) ) {
2393
2394     &{ $verify{$verify} }( $p, $cust_main )
2395       or return { 'error' => 'Account not found' };
2396
2397   }
2398
2399   #we're verified.  now what?
2400  
2401
2402   return { 'error' => '' };
2403 }
2404
2405
2406 sub create_ticket {
2407   my $p = shift;
2408   my($context, $session, $custnum) = _custoragent_session_custnum($p);
2409   return { 'error' => $session } if $context eq 'error';
2410
2411   warn "$me create_ticket: initializing ticket system\n" if $DEBUG;
2412   FS::TicketSystem->init();
2413
2414   my $conf = new FS::Conf;
2415   my $queue = $p->{'queue'}
2416               || $conf->config('ticket_system-selfservice_queueid')
2417               || $conf->config('ticket_system-default_queueid');
2418
2419   warn "$me create_ticket: creating ticket\n" if $DEBUG;
2420   my $err_or_ticket = FS::TicketSystem->create_ticket(
2421     '', #create RT session based on FS CurrentUser (fs_selfservice)
2422     'queue'   => $queue,
2423     'custnum' => $custnum,
2424     'svcnum'  => $session->{'svcnum'},
2425     map { $_ => $p->{$_} } qw( requestor cc subject message mime_type )
2426   );
2427
2428   if ( ref($err_or_ticket) ) {
2429     warn "$me create_ticket: successful: ". $err_or_ticket->id. "\n"
2430       if $DEBUG;
2431     return { 'error'     => '',
2432              'ticket_id' => $err_or_ticket->id,
2433            };
2434   } else {
2435     warn "$me create_ticket: unsuccessful: $err_or_ticket\n"
2436       if $DEBUG;
2437     return { 'error' => $err_or_ticket };
2438   }
2439
2440
2441 }
2442
2443 sub did_report {
2444   my $p = shift;
2445   my($context, $session, $custnum) = _custoragent_session_custnum($p);
2446   return { 'error' => $session } if $context eq 'error';
2447  
2448   return { error => 'requested format not implemented' } 
2449     unless ($p->{'format'} eq 'csv' || $p->{'format'} eq 'xls');
2450
2451   my $conf = new FS::Conf;
2452   my $age_threshold = 0;
2453   $age_threshold = time() - $conf->config('selfservice-recent-did-age')
2454     if ($p->{'recentonly'} && $conf->exists('selfservice-recent-did-age'));
2455
2456   my $search = { 'custnum' => $custnum };
2457   $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2458   my $cust_main = qsearchs('cust_main', $search )
2459     or return { 'error' => "unknown custnum $custnum" };
2460
2461 # does it make more sense to just run one sql query for this instead of all the
2462 # insanity below? would increase performance greately for large data sets?
2463   my @svc_phone = ();
2464   foreach my $cust_pkg ( $cust_main->ncancelled_pkgs ) {
2465         my @part_svc = $cust_pkg->part_svc;
2466         foreach my $part_svc ( @part_svc ) {
2467             if($part_svc->svcdb eq 'svc_phone'){
2468                 my @cust_pkg_svc = @{$part_svc->cust_pkg_svc};
2469                 foreach my $cust_pkg_svc ( @cust_pkg_svc ) {
2470                     push @svc_phone, $cust_pkg_svc->svc_x
2471                         if $cust_pkg_svc->date_inserted >= $age_threshold;
2472                 }
2473             }
2474         }
2475   }
2476
2477   my $csv;
2478   my $xls;
2479   my($xls_r,$xls_c) = (0,0);
2480   my $xls_workbook;
2481   my $content = '';
2482   my @fields = qw( countrycode phonenum pin sip_password phone_name );
2483   if($p->{'format'} eq 'csv') {
2484     $csv = new Text::CSV_XS { 'always_quote' => 1,
2485                                  'eol'          => "\n",
2486                                 };
2487     return { 'error' => 'Unable to create CSV' } unless $csv->combine(@fields);
2488     $content .= $csv->string;
2489   }
2490   elsif($p->{'format'} eq 'xls') {
2491     my $XLS1 = new IO::Scalar \$content;
2492     $xls_workbook = Spreadsheet::WriteExcel->new($XLS1) 
2493         or return { 'error' => "Error opening .xls file: $!" };
2494     $xls = $xls_workbook->add_worksheet('DIDs');
2495     foreach ( @fields ) {
2496         $xls->write(0,$xls_c++,$_);
2497     }
2498     $xls_r++;
2499   }
2500
2501   foreach my $svc_phone ( @svc_phone ) {
2502     my @cols = map { $svc_phone->$_ } @fields;
2503     if($p->{'format'} eq 'csv') {
2504         return { 'error' => 'Unable to create CSV' } 
2505             unless $csv->combine(@cols);
2506         $content .= $csv->string;
2507     }
2508     elsif($p->{'format'} eq 'xls') {
2509         $xls_c = 0;
2510         foreach ( @cols ) {
2511             $xls->write($xls_r,$xls_c++,$_);
2512         }
2513         $xls_r++;
2514     }
2515   }
2516
2517   $xls_workbook->close() if $p->{'format'} eq 'xls';
2518   
2519   { content => $content, format => $p->{'format'}, };
2520 }
2521
2522 sub get_ticket {
2523   my $p = shift;
2524   my($context, $session, $custnum) = _custoragent_session_custnum($p);
2525   return { 'error' => $session } if $context eq 'error';
2526
2527   warn "$me get_ticket: initializing ticket system\n" if $DEBUG;
2528   FS::TicketSystem->init();
2529   return { 'error' => 'get_ticket configuration error' }
2530     if $FS::TicketSystem::system ne 'RT_Internal';
2531
2532   # check existence and ownership as part of this
2533   warn "$me get_ticket: fetching ticket\n" if $DEBUG;
2534   my $rt_session = FS::TicketSystem->session('');
2535   my $Ticket = FS::TicketSystem->get_ticket_object(
2536     $rt_session, 
2537     ticket_id => $p->{'ticket_id'},
2538     custnum => $custnum
2539   );
2540   return { 'error' => 'ticket not found' } if !$Ticket;
2541
2542   if ( length( $p->{'subject'} || '' ) ) {
2543     # subject change
2544     if ( $p->{'subject'} ne $Ticket->Subject ) {
2545       my ($val, $msg) = $Ticket->SetSubject($p->{'subject'});
2546       return { 'error' => "unable to set subject: $msg" } if !$val;
2547     }
2548   }
2549
2550   if(length($p->{'reply'})) {
2551     my @err_or_res = FS::TicketSystem->correspond_ticket(
2552       $rt_session,
2553       'ticket_id' => $p->{'ticket_id'},
2554       'content' => $p->{'reply'},
2555     );
2556
2557     return { 'error' => 'unable to reply to ticket' } 
2558     unless ( $err_or_res[0] != 0 && defined $err_or_res[2] );
2559   }
2560
2561   warn "$me get_ticket: getting ticket history\n" if $DEBUG;
2562   my $err_or_ticket = FS::TicketSystem->get_ticket(
2563     $rt_session,
2564     'ticket_id' => $p->{'ticket_id'},
2565   );
2566
2567   if ( !ref($err_or_ticket) ) { # there is no way this should ever happen
2568     warn "$me get_ticket: unsuccessful: $err_or_ticket\n"
2569       if $DEBUG;
2570     return { 'error' => $err_or_ticket };
2571   }
2572
2573   my @custs = @{$err_or_ticket->{'custs'}};
2574   my @txns = @{$err_or_ticket->{'txns'}};
2575   my @filtered_txns;
2576
2577   # superseded by check in get_ticket_object
2578   #return { 'error' => 'invalid ticket requested' } 
2579   #unless grep($_ eq $custnum, @custs);
2580
2581   foreach my $txn ( @txns ) {
2582     push @filtered_txns, $txn 
2583     if ($txn->{'type'} eq 'EmailRecord' 
2584       || $txn->{'type'} eq 'Correspond'
2585       || $txn->{'type'} eq 'Create');
2586   }
2587
2588   warn "$me get_ticket: successful: \n"
2589   if $DEBUG;
2590   return { 'error'     => '',
2591     'transactions' => \@filtered_txns,
2592     'ticket_fields' => $err_or_ticket->{'fields'},
2593     'ticket_id' => $p->{'ticket_id'},
2594   };
2595 }
2596
2597 sub adjust_ticket_priority {
2598   my $p = shift;
2599   my($context, $session, $custnum) = _custoragent_session_custnum($p);
2600   return { 'error' => $session } if $context eq 'error';
2601
2602   warn "$me adjust_ticket_priority: initializing ticket system\n" if $DEBUG;
2603   FS::TicketSystem->init;
2604   my $ss_priority = FS::TicketSystem->selfservice_priority;
2605
2606   return { 'error' => 'adjust_ticket_priority configuration error' }
2607     if $FS::TicketSystem::system ne 'RT_Internal'
2608       or !$ss_priority;
2609
2610   my $values = $p->{'values'}; #hashref, id => priority value
2611   my %ticket_error;
2612
2613   foreach my $id (keys %$values) {
2614     warn "$me adjust_ticket_priority: fetching ticket $id\n" if $DEBUG;
2615     my $Ticket = FS::TicketSystem->get_ticket_object('',
2616       'ticket_id' => $id,
2617       'custnum'   => $custnum,
2618     );
2619     if ( !$Ticket ) {
2620       $ticket_error{$id} = 'ticket not found';
2621       next;
2622     }
2623     
2624   # RT API stuff--would we gain anything by wrapping this in FS::TicketSystem?
2625   # We're not going to implement it for RT_External.
2626     my $old_value = $Ticket->FirstCustomFieldValue($ss_priority);
2627     my $new_value = $values->{$id};
2628     next if $old_value eq $new_value;
2629
2630     warn "$me adjust_ticket_priority: updating ticket $id\n" if $DEBUG;
2631
2632     # AddCustomFieldValue works fine (replacing any existing value) if it's 
2633     # a single-valued custom field, which it should be.  If it's not, you're 
2634     # doing something wrong.
2635     my ($val, $msg);
2636     if ( length($new_value) ) {
2637       ($val, $msg) = $Ticket->AddCustomFieldValue( 
2638         Field => $ss_priority,
2639         Value => $new_value,
2640       );
2641     }
2642     else {
2643       ($val, $msg) = $Ticket->DeleteCustomFieldValue(
2644         Field => $ss_priority,
2645         Value => $old_value,
2646       );
2647     }
2648
2649     $ticket_error{$id} = $msg if !$val;
2650     warn "$me adjust_ticket_priority: $id: $msg\n" if $DEBUG and !$val;
2651   }
2652   return { 'error' => '',
2653            'ticket_error' => \%ticket_error,
2654            %{ customer_info($p) } # send updated customer info back
2655          }
2656 }
2657
2658 #--
2659
2660 sub _custoragent_session_custnum {
2661   my $p = shift;
2662
2663   my($context, $session, $custnum);
2664   if ( $p->{'session_id'} ) {
2665
2666     $context = 'customer';
2667     $session = _cache->get($p->{'session_id'})
2668       or return ( 'error' => "Can't resume session" ); #better error message
2669     $custnum = $session->{'custnum'};
2670
2671   } elsif ( $p->{'agent_session_id'} ) {
2672
2673     $context = 'agent';
2674     my $agent_cache = new FS::ClientAPI_SessionCache( {
2675       'namespace' => 'FS::ClientAPI::Agent',
2676     } );
2677     $session = $agent_cache->get($p->{'agent_session_id'})
2678       or return ( 'error' => "Can't resume session" ); #better error message
2679     $custnum = $p->{'custnum'};
2680
2681   } else {
2682     $context = 'error';
2683     return ( 'error' => "Can't resume session" ); #better error message
2684   }
2685
2686   ($context, $session, $custnum);
2687
2688 }
2689
2690 1;
2691