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            'invoice_html' => $legacy_cust_bill->content_html,
1166          };
1167
1168 }
1169
1170 sub legacy_invoice_pdf {
1171   my $p = shift;
1172   my $session = _cache->get($p->{'session_id'})
1173     or return { 'error' => "Can't resume session" }; #better error message
1174
1175   my $custnum = $session->{'custnum'};
1176
1177   my $legacyinvnum = $p->{'legacyinvnum'};
1178
1179   my $legacy_cust_bill = qsearchs('legacy_cust_bill', {
1180     'legacyinvnum' => $legacyinvnum,
1181     'custnum'      => $custnum,
1182   }) or return { 'error' => "Can't find legacyinvnum" };
1183
1184   #my %return;
1185
1186   return { 'error'        => '',
1187            'legacyinvnum' => $legacyinvnum,
1188            'invoice_pdf'  => $legacy_cust_bill->content_pdf,
1189          };
1190
1191 }
1192
1193 sub invoice_logo {
1194   my $p = shift;
1195
1196   #sessioning for this?  how do we get the session id to the backend invoice
1197   # template so it can add it to the link, blah
1198
1199   my $agentnum = '';
1200   if ( $p->{'invnum'} ) {
1201     my $cust_bill = qsearchs('cust_bill', { 'invnum' => $p->{'invnum'} } )
1202       or return { 'error' => 'unknown invnum' };
1203     $agentnum = $cust_bill->cust_main->agentnum;
1204   }
1205
1206   my $templatename = $p->{'template'} || $p->{'templatename'};
1207
1208   #false laziness-ish w/view/cust_bill-logo.cgi
1209
1210   my $conf = new FS::Conf;
1211   if ( $templatename =~ /^([^\.\/]*)$/ && $conf->exists("logo_$1.png") ) {
1212     $templatename = "_$1";
1213   } else {
1214     $templatename = '';
1215   }
1216
1217   my $filename = "logo$templatename.png";
1218
1219   return { 'error'        => '',
1220            'logo'         => $conf->config_binary($filename, $agentnum),
1221            'content_type' => 'image/png', #should allow gif, jpg too
1222          };
1223 }
1224
1225
1226 sub list_invoices {
1227   my $p = shift;
1228   my $session = _cache->get($p->{'session_id'})
1229     or return { 'error' => "Can't resume session" }; #better error message
1230
1231   my $custnum = $session->{'custnum'};
1232
1233   my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1234     or return { 'error' => "unknown custnum $custnum" };
1235
1236   my @cust_bill = $cust_main->cust_bill;
1237   my @legacy_cust_bill = $cust_main->legacy_cust_bill;
1238
1239   my $balance = 0;
1240
1241   return  { 'error'       => '',
1242             'balance'     => $cust_main->balance,
1243             'invoices'    => [
1244               map {
1245                     my $owed = $_->owed;
1246                     $balance += $owed;
1247                     +{ 'invnum'       => $_->invnum,
1248                        '_date'        => $_->_date,
1249                        'date'         => time2str("%b %o, %Y", $_->_date),
1250                        'date_short'   => time2str("%m-%d-%Y",  $_->_date),
1251                        'previous'     => sprintf('%.2f', ($_->previous)[0]),
1252                        'charged'      => sprintf('%.2f', $_->charged),
1253                        'owed'         => sprintf('%.2f', $owed),
1254                        'balance'      => sprintf('%.2f', $balance),
1255                      }
1256                   }
1257                   @cust_bill
1258             ],
1259             'legacy_invoices' => [
1260               map {
1261                     +{ 'legacyinvnum' => $_->legacyinvnum,
1262                        'legacyid'     => $_->legacyid,
1263                        '_date'        => $_->_date,
1264                        'date'         => time2str("%b %o, %Y", $_->_date),
1265                        'date_short'   => time2str("%m-%d-%Y",  $_->_date),
1266                        'charged'      => sprintf('%.2f', $_->charged),
1267                        'has_content'  => (    length($_->content_pdf)
1268                                            || length($_->content_html) ),
1269                      }
1270                   }
1271                   @legacy_cust_bill
1272             ],
1273           };
1274 }
1275
1276 sub cancel {
1277   my $p = shift;
1278   my $session = _cache->get($p->{'session_id'})
1279     or return { 'error' => "Can't resume session" }; #better error message
1280
1281   my $custnum = $session->{'custnum'};
1282
1283   my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1284     or return { 'error' => "unknown custnum $custnum" };
1285
1286   my @errors = $cust_main->cancel( 'quiet'=>1 );
1287
1288   my $error = scalar(@errors) ? join(' / ', @errors) : '';
1289
1290   return { 'error' => $error };
1291
1292 }
1293
1294 sub list_pkgs {
1295   my $p = shift;
1296
1297   my($context, $session, $custnum) = _custoragent_session_custnum($p);
1298   return { 'error' => $session } if $context eq 'error';
1299
1300   my $search = { 'custnum' => $custnum };
1301   $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
1302   my $cust_main = qsearchs('cust_main', $search )
1303     or return { 'error' => "unknown custnum $custnum" };
1304
1305   my $conf = new FS::Conf;
1306   
1307 # the duplication below is necessary:
1308 # 1. to maintain the current buggy behaviour wrt the cust_pkg and part_pkg
1309 # hashes overwriting each other (setup and no_auto fields). Fixing that is a
1310 # non-backwards-compatible change breaking the software of anyone using the API
1311 # instead of the stock selfservice
1312 # 2. to return cancelled packages as well - for wholesale and non-wholesale
1313   if( $conf->exists('selfservice_server-view-wholesale') ) {
1314     return { 'svcnum'   => $session->{'svcnum'},
1315             'custnum'  => $custnum,
1316             'cust_pkg' => [ map {
1317                           { $_->hash,
1318                             part_pkg => [ map $_->hashref, $_->part_pkg ],
1319                             part_svc =>
1320                               [ map $_->hashref, $_->available_part_svc ],
1321                             cust_svc => 
1322                               [ map { my $ref = { $_->hash,
1323                                                   label => [ $_->label ],
1324                                                 };
1325                                       $ref->{_password} = $_->svc_x->_password
1326                                         if $context eq 'agent'
1327                                         && $conf->exists('agent-showpasswords')
1328                                         && $_->part_svc->svcdb eq 'svc_acct';
1329                                       $ref;
1330                                     } $_->cust_svc
1331                               ],
1332                           };
1333                         } $cust_main->cust_pkg
1334                   ],
1335     'small_custview' =>
1336       small_custview( $cust_main, $conf->config('countrydefault') ),
1337     'wholesale_view' => 1,
1338     'login_svcpart' => [ $conf->config('selfservice_server-login_svcpart') ],
1339     'date_format' => $conf->config('date_format') || '%m/%d/%Y',
1340     'lnp' => $conf->exists('svc_phone-lnp'),
1341       };
1342   }
1343
1344   { 'svcnum'   => $session->{'svcnum'},
1345     'custnum'  => $custnum,
1346     'cust_pkg' => [ map {
1347                           my $primary_cust_svc = $_->primary_cust_svc;
1348                           +{ $_->hash,
1349                             $_->part_pkg->hash,
1350                             status => $_->status,
1351                             part_svc =>
1352                               [ map $_->hashref, $_->available_part_svc ],
1353                             cust_svc => 
1354                               [ map { my $ref = { $_->hash,
1355                                                   label => [ $_->label ],
1356                                                 };
1357                                       $ref->{_password} = $_->svc_x->_password
1358                                         if $context eq 'agent'
1359                                         && $conf->exists('agent-showpasswords')
1360                                         && $_->part_svc->svcdb eq 'svc_acct';
1361                                       $ref->{svchash} = { $_->svc_x->hash } if 
1362                                         $_->part_svc->svcdb eq 'svc_phone';
1363                                       $ref->{svchash}->{svcpart} =  $_->part_svc->svcpart
1364                                         if $_->part_svc->svcdb eq 'svc_phone'; # hack
1365                                       $ref;
1366                                     } $_->cust_svc
1367                               ],
1368                             primary_cust_svc =>
1369                               $primary_cust_svc
1370                                 ? { $primary_cust_svc->hash,
1371                                     label => [ $primary_cust_svc->label ],
1372                                     finger => $primary_cust_svc->svc_x->finger, #uuh
1373                                     $primary_cust_svc->part_svc->hash,
1374                                   }
1375                                 : {}, #'' ?
1376                           };
1377                         } $cust_main->ncancelled_pkgs
1378                   ],
1379     'small_custview' =>
1380       small_custview( $cust_main, $conf->config('countrydefault') ),
1381   };
1382
1383 }
1384
1385 sub list_svcs {
1386   my $p = shift;
1387
1388   my($context, $session, $custnum) = _custoragent_session_custnum($p);
1389   return { 'error' => $session } if $context eq 'error';
1390
1391   my $search = { 'custnum' => $custnum };
1392   $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
1393   my $cust_main = qsearchs('cust_main', $search )
1394     or return { 'error' => "unknown custnum $custnum" };
1395
1396   my $pkgnum = $session->{'pkgnum'} || $p->{'pkgnum'} || '';
1397   if ( ! $pkgnum && $p->{'svcnum'} ) {
1398     my $cust_svc = qsearchs('cust_svc', { 'svcnum' => $p->{'svcnum'} } );
1399     $pkgnum = $cust_svc->pkgnum if $cust_svc;
1400   }
1401
1402   my @cust_svc = ();
1403   #foreach my $cust_pkg ( $cust_main->ncancelled_pkgs ) {
1404   foreach my $cust_pkg ( $p->{'ncancelled'} 
1405                          ? $cust_main->ncancelled_pkgs
1406                          : $cust_main->unsuspended_pkgs ) {
1407     next if $pkgnum && $cust_pkg->pkgnum != $pkgnum;
1408     push @cust_svc, @{[ $cust_pkg->cust_svc ]}; #@{[ ]} to force array context
1409   }
1410   if ( $p->{'svcdb'} ) {
1411     my $svcdb = ref($p->{'svcdb'}) eq 'HASH'
1412                   ? $p->{'svcdb'}
1413                   : ref($p->{'svcdb'}) eq 'ARRAY'
1414                     ? { map { $_=>1 } @{ $p->{'svcdb'} } }
1415                     : { $p->{'svcdb'} => 1 };
1416     @cust_svc = grep $svcdb->{ $_->part_svc->svcdb }, @cust_svc
1417   }
1418
1419   #@svc_x = sort { $a->domain cmp $b->domain || $a->username cmp $b->username }
1420   #              @svc_x;
1421
1422     my $conf = new FS::Conf;
1423
1424   { 
1425     'svcnum'   => $session->{'svcnum'},
1426     'custnum'  => $custnum,
1427     'date_format' => $conf->config('date_format') || '%m/%d/%Y',
1428     'view_usage_nodomain' => $conf->exists('selfservice-view_usage_nodomain'),
1429     'svcs'     => [
1430       map { 
1431             my $svc_x = $_->svc_x;
1432             my($label, $value) = $_->label;
1433             my $svcdb = $_->part_svc->svcdb;
1434             my $part_pkg = $_->cust_pkg->part_pkg;
1435
1436             my %hash = (
1437               'svcnum' => $_->svcnum,
1438               'svcdb'  => $svcdb,
1439               'label'  => $label,
1440               'value'  => $value,
1441             );
1442
1443             if ( $svcdb eq 'svc_acct' ) {
1444               %hash = (
1445                 %hash,
1446                 'username'   => $svc_x->username,
1447                 'email'      => $svc_x->email,
1448                 'finger'     => $svc_x->finger,
1449                 'seconds'    => $svc_x->seconds,
1450                 'upbytes'    => display_bytecount($svc_x->upbytes),
1451                 'downbytes'  => display_bytecount($svc_x->downbytes),
1452                 'totalbytes' => display_bytecount($svc_x->totalbytes),
1453
1454                 'recharge_amount'  => $part_pkg->option('recharge_amount',1),
1455                 'recharge_seconds' => $part_pkg->option('recharge_seconds',1),
1456                 'recharge_upbytes'    =>
1457                   display_bytecount($part_pkg->option('recharge_upbytes',1)),
1458                 'recharge_downbytes'  =>
1459                   display_bytecount($part_pkg->option('recharge_downbytes',1)),
1460                 'recharge_totalbytes' =>
1461                   display_bytecount($part_pkg->option('recharge_totalbytes',1)),
1462                 # more...
1463               );
1464
1465             } elsif ( $svcdb eq 'svc_dsl' ) {
1466               $hash{'phonenum'} = $svc_x->phonenum;
1467               if ( $svc_x->first || $svc_x->get('last') || $svc_x->company ) {
1468                 $hash{'name'} = $svc_x->first. ' '. $svc_x->get('last');
1469                 $hash{'name'} = $svc_x->company. ' ('. $hash{'name'}. ')'
1470                   if $svc_x->company;
1471               } else {
1472                 $hash{'name'} = $cust_main->name;
1473               }
1474             }
1475             # elsif ( $svcdb eq 'svc_phone' || $svcdb eq 'svc_port' ) {
1476             #  %hash = (
1477             #    %hash,
1478             #  );
1479             #}
1480
1481             \%hash;
1482           }
1483           @cust_svc
1484     ],
1485   };
1486
1487 }
1488
1489 sub _customer_svc_x {
1490   my($custnum, $svcnum, $table) = @_;
1491
1492   $custnum =~ /^(\d+)$/ or die "illegal custnum";
1493   my $search = " AND custnum = $1";
1494   #$search .= " AND agentnum = ". $session->{'agentnum'} if $context eq 'agent';
1495
1496   qsearchs( {
1497     'table'     => ($table || 'svc_acct'),
1498     'addl_from' => 'LEFT JOIN cust_svc  USING ( svcnum  ) '.
1499                    'LEFT JOIN cust_pkg  USING ( pkgnum  ) ',#.
1500                    #'LEFT JOIN cust_main USING ( custnum ) ',
1501     'hashref'   => { 'svcnum' => $svcnum, },
1502     'extra_sql' => $search, #important
1503   } );
1504
1505 }
1506
1507 sub list_dsl_devices {
1508   my $p = shift;
1509
1510   my($context, $session, $custnum) = _custoragent_session_custnum($p);
1511   return { 'error' => $session } if $context eq 'error';
1512
1513   my $svc_dsl = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_dsl' )
1514     or return { 'error' => "Service not found" };
1515
1516   return {
1517     'devices' => [ map {
1518                          +{ 'mac_addr' => $_->mac_addr };
1519                        } $svc_dsl->dsl_device
1520                  ],
1521   };
1522
1523 }
1524
1525 sub add_dsl_device {
1526   my $p = shift;
1527
1528   my($context, $session, $custnum) = _custoragent_session_custnum($p);
1529   return { 'error' => $session } if $context eq 'error';
1530
1531   my $svc_dsl = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_dsl' )
1532     or return { 'error' => "Service not found" };
1533
1534   return { 'error' => 'No MAC address supplied' }
1535     unless length($p->{'mac_addr'});
1536
1537   my $dsl_device = new FS::dsl_device { 'svcnum'   => $svc_dsl->svcnum,
1538                                         'mac_addr' => scalar($p->{'mac_addr'}),
1539                                       };
1540   my $error = $dsl_device->insert;
1541   return { 'error' => $error };
1542
1543 }
1544
1545 sub delete_dsl_device {
1546   my $p = shift;
1547
1548   my($context, $session, $custnum) = _custoragent_session_custnum($p);
1549   return { 'error' => $session } if $context eq 'error';
1550
1551   my $svc_dsl = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_dsl' )
1552     or return { 'error' => "Service not found" };
1553
1554   my $dsl_device = qsearchs('dsl_device', { 'svcnum'   => $svc_dsl->svcnum,
1555                                             'mac_addr' => scalar($p->{'mac_addr'}),
1556                                           }
1557                            )
1558     or return { 'error' => 'Unknown MAC address: '. $p->{'mac_addr'} };
1559
1560   my $error = $dsl_device->delete;
1561   return { 'error' => $error };
1562
1563 }
1564
1565 sub port_graph {
1566   my $p = shift;
1567   _usage_details( \&_port_graph, $p,
1568                   'svcdb' => 'svc_port',
1569                 );
1570 }
1571
1572 sub _port_graph {
1573   my($svc_port, $begin, $end) = @_;
1574   my @usage = ();
1575   my $pngOrError = $svc_port->graph_png( start=>$begin, end=> $end );
1576   push @usage, { 'png' => $pngOrError };
1577   (@usage);
1578 }
1579
1580 sub _list_svc_usage {
1581   my($svc_acct, $begin, $end) = @_;
1582   my @usage = ();
1583   foreach my $part_export ( 
1584     map { qsearch ( 'part_export', { 'exporttype' => $_ } ) }
1585     qw( sqlradius sqlradius_withdomain )
1586   ) {
1587     push @usage, @ { $part_export->usage_sessions($begin, $end, $svc_acct) };
1588   }
1589   (@usage);
1590 }
1591
1592 sub list_svc_usage {
1593   _usage_details(\&_list_svc_usage, @_);
1594 }
1595
1596 sub _list_support_usage {
1597   my($svc_acct, $begin, $end) = @_;
1598   my @usage = ();
1599   foreach ( grep { $begin <= $_->_date && $_->_date <= $end }
1600             qsearch('acct_rt_transaction', { 'svcnum' => $svc_acct->svcnum })
1601           ) {
1602     push @usage, { 'seconds'  => $_->seconds,
1603                    'support'  => $_->support,
1604                    '_date'    => $_->_date,
1605                    'id'       => $_->transaction_id,
1606                    'creator'  => $_->creator,
1607                    'subject'  => $_->subject,
1608                    'status'   => $_->status,
1609                    'ticketid' => $_->ticketid,
1610                  };
1611   }
1612   (@usage);
1613 }
1614
1615 sub list_support_usage {
1616   _usage_details(\&_list_support_usage, @_);
1617 }
1618
1619 sub _list_cdr_usage {
1620   my($svc_phone, $begin, $end) = @_;
1621   map [ $_->downstream_csv('format' => 'default', 'keeparray' => 1) ], #XXX config for format
1622                        $svc_phone->get_cdrs( 'begin'=>$begin, 'end'=>$end, );
1623 }
1624
1625 sub list_cdr_usage {
1626   my $p = shift;
1627   _usage_details( \&_list_cdr_usage, $p,
1628                   'svcdb' => 'svc_phone',
1629                 );
1630 }
1631
1632 sub _usage_details {
1633   my($callback, $p, %opt) = @_;
1634
1635   my($context, $session, $custnum) = _custoragent_session_custnum($p);
1636   return { 'error' => $session } if $context eq 'error';
1637
1638   my $search = { 'svcnum' => $p->{'svcnum'} };
1639   $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
1640
1641   my $svcdb = $opt{'svcdb'} || 'svc_acct';
1642
1643   my $svc_x = qsearchs( $svcdb, $search );
1644   return { 'error' => 'No service selected in list_svc_usage' } 
1645     unless $svc_x;
1646
1647   my $header = $svcdb eq 'svc_phone'
1648                  ? [ split(',', FS::cdr::invoice_header('default') ) ]  #XXX
1649                  : [];
1650
1651   my $cust_pkg = $svc_x->cust_svc->cust_pkg;
1652   my $freq     = $cust_pkg->part_pkg->freq;
1653   my $start    = $cust_pkg->setup;
1654   #my $end      = $cust_pkg->bill; # or time?
1655   my $end      = time;
1656
1657   unless ( $p->{beginning} ) {
1658     $p->{beginning} = $cust_pkg->last_bill;
1659     $p->{ending}    = $end;
1660   }
1661
1662   my (@usage) = &$callback($svc_x, $p->{beginning}, $p->{ending});
1663
1664   #kinda false laziness with FS::cust_main::bill, but perhaps
1665   #we should really change this bit to DateTime and DateTime::Duration
1666   #
1667   #change this bit to use Date::Manip? CAREFUL with timezones (see
1668   # mailing list archive)
1669   my ($nsec,$nmin,$nhour,$nmday,$nmon,$nyear) =
1670     (localtime($p->{ending}) )[0,1,2,3,4,5];
1671   my ($psec,$pmin,$phour,$pmday,$pmon,$pyear) =
1672     (localtime($p->{beginning}) )[0,1,2,3,4,5];
1673
1674   if ( $freq =~ /^\d+$/ ) {
1675     $nmon += $freq;
1676     until ( $nmon < 12 ) { $nmon -= 12; $nyear++; }
1677     $pmon -= $freq;
1678     until ( $pmon >= 0 ) { $pmon += 12; $pyear--; }
1679   } elsif ( $freq =~ /^(\d+)w$/ ) {
1680     my $weeks = $1;
1681     $nmday += $weeks * 7;
1682     $pmday -= $weeks * 7;
1683   } elsif ( $freq =~ /^(\d+)d$/ ) {
1684     my $days = $1;
1685     $nmday += $days;
1686     $pmday -= $days;
1687   } elsif ( $freq =~ /^(\d+)h$/ ) {
1688     my $hours = $1;
1689     $nhour += $hours;
1690     $phour -= $hours;
1691   } else {
1692     return { 'error' => "unparsable frequency: ". $freq };
1693   }
1694   
1695   my $previous  = timelocal_nocheck($psec,$pmin,$phour,$pmday,$pmon,$pyear);
1696   my $next      = timelocal_nocheck($nsec,$nmin,$nhour,$nmday,$nmon,$nyear);
1697
1698   { 
1699     'error'     => '',
1700     'svcnum'    => $p->{svcnum},
1701     'beginning' => $p->{beginning},
1702     'ending'    => $p->{ending},
1703     'previous'  => ($previous > $start) ? $previous : $start,
1704     'next'      => ($next < $end) ? $next : $end,
1705     'header'    => $header,
1706     'usage'     => \@usage,
1707   };
1708 }
1709
1710 sub order_pkg {
1711   my $p = shift;
1712
1713   my($context, $session, $custnum) = _custoragent_session_custnum($p);
1714   return { 'error' => $session } if $context eq 'error';
1715
1716   my $search = { 'custnum' => $custnum };
1717   $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
1718   my $cust_main = qsearchs('cust_main', $search )
1719     or return { 'error' => "unknown custnum $custnum" };
1720
1721   my $status = $cust_main->status;
1722   #false laziness w/ClientAPI/Signup.pm
1723
1724   my $cust_pkg = new FS::cust_pkg ( {
1725     'custnum' => $custnum,
1726     'pkgpart' => $p->{'pkgpart'},
1727   } );
1728   my $error = $cust_pkg->check;
1729   return { 'error' => $error } if $error;
1730
1731   my @svc = ();
1732   unless ( $p->{'svcpart'} eq 'none' ) {
1733
1734     my $svcdb;
1735     my $svcpart = '';
1736     if ( $p->{'svcpart'} =~ /^(\d+)$/ ) {
1737       $svcpart = $1;
1738       my $part_svc = qsearchs('part_svc', { 'svcpart' => $svcpart } );
1739       return { 'error' => "Unknown svcpart $svcpart" } unless $part_svc;
1740       $svcdb = $part_svc->svcdb;
1741     } else {
1742       $svcdb = 'svc_acct';
1743     }
1744     $svcpart ||= $cust_pkg->part_pkg->svcpart($svcdb);
1745
1746     my %fields = (
1747       'svc_acct'     => [ qw( username domsvc _password sec_phrase popnum ) ],
1748       'svc_domain'   => [ qw( domain ) ],
1749       'svc_phone'    => [ qw( phonenum pin sip_password phone_name ) ],
1750       'svc_external' => [ qw( id title ) ],
1751       'svc_pbx'      => [ qw( id title ) ],
1752     );
1753   
1754     my $svc_x = "FS::$svcdb"->new( {
1755       'svcpart'   => $svcpart,
1756       map { $_ => $p->{$_} } @{$fields{$svcdb}}
1757     } );
1758     
1759     if ( $svcdb eq 'svc_acct' && exists($p->{"snarf_machine1"}) ) {
1760       my @acct_snarf;
1761       my $snarfnum = 1;
1762       while ( length($p->{"snarf_machine$snarfnum"}) ) {
1763         my $acct_snarf = new FS::acct_snarf ( {
1764           'machine'   => $p->{"snarf_machine$snarfnum"},
1765           'protocol'  => $p->{"snarf_protocol$snarfnum"},
1766           'username'  => $p->{"snarf_username$snarfnum"},
1767           '_password' => $p->{"snarf_password$snarfnum"},
1768         } );
1769         $snarfnum++;
1770         push @acct_snarf, $acct_snarf;
1771       }
1772       $svc_x->child_objects( \@acct_snarf );
1773     }
1774     
1775     my $y = $svc_x->setdefault; # arguably should be in new method
1776     return { 'error' => $y } if $y && !ref($y);
1777   
1778     $error = $svc_x->check;
1779     return { 'error' => $error } if $error;
1780
1781     push @svc, $svc_x;
1782
1783   }
1784
1785   use Tie::RefHash;
1786   tie my %hash, 'Tie::RefHash';
1787   %hash = ( $cust_pkg => \@svc );
1788   #msgcat
1789   $error = $cust_main->order_pkgs( \%hash, 'noexport' => 1 );
1790   return { 'error' => $error } if $error;
1791
1792   my $conf = new FS::Conf;
1793   if ( $conf->exists('signup_server-realtime') ) {
1794
1795     my $bill_error = _do_bop_realtime( $cust_main, $status );
1796
1797     if ($bill_error) {
1798       $cust_pkg->cancel('quiet'=>1);
1799       return $bill_error;
1800     } else {
1801       $cust_pkg->reexport;
1802     }
1803
1804   } else {
1805     $cust_pkg->reexport;
1806   }
1807
1808   my $svcnum = $svc[0] ? $svc[0]->svcnum : '';
1809
1810   return { error=>'', pkgnum=>$cust_pkg->pkgnum, svcnum=>$svcnum };
1811
1812 }
1813
1814 sub change_pkg {
1815   my $p = shift;
1816
1817   my($context, $session, $custnum) = _custoragent_session_custnum($p);
1818   return { 'error' => $session } if $context eq 'error';
1819
1820   my $search = { 'custnum' => $custnum };
1821   $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
1822   my $cust_main = qsearchs('cust_main', $search )
1823     or return { 'error' => "unknown custnum $custnum" };
1824
1825   my $status = $cust_main->status;
1826   my $cust_pkg = qsearchs('cust_pkg', { 'pkgnum' => $p->{pkgnum} } )
1827     or return { 'error' => "unknown package $p->{pkgnum}" };
1828
1829   my @newpkg;
1830   my $error = FS::cust_pkg::order( $custnum,
1831                                    [$p->{pkgpart}],
1832                                    [$p->{pkgnum}],
1833                                    \@newpkg,
1834                                  );
1835
1836   my $conf = new FS::Conf;
1837   if ( $conf->exists('signup_server-realtime') ) {
1838
1839     my $bill_error = _do_bop_realtime( $cust_main, $status );
1840
1841     if ($bill_error) {
1842       $newpkg[0]->suspend;
1843       return $bill_error;
1844     } else {
1845       $newpkg[0]->reexport;
1846     }
1847
1848   } else {  
1849     $newpkg[0]->reexport;
1850   }
1851
1852   return { error => '', pkgnum => $cust_pkg->pkgnum };
1853
1854 }
1855
1856 sub order_recharge {
1857   my $p = shift;
1858
1859   my($context, $session, $custnum) = _custoragent_session_custnum($p);
1860   return { 'error' => $session } if $context eq 'error';
1861
1862   my $search = { 'custnum' => $custnum };
1863   $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
1864   my $cust_main = qsearchs('cust_main', $search )
1865     or return { 'error' => "unknown custnum $custnum" };
1866
1867   my $status = $cust_main->status;
1868   my $cust_svc = qsearchs( 'cust_svc', { 'svcnum' => $p->{'svcnum'} } )
1869     or return { 'error' => "unknown service " . $p->{'svcnum'} };
1870
1871   my $svc_x = $cust_svc->svc_x;
1872   my $part_pkg = $cust_svc->cust_pkg->part_pkg;
1873
1874   my %vhash =
1875     map { $_ =~ /^recharge_(.*)$/; $1, $part_pkg->option($_, 1) } 
1876     qw ( recharge_seconds recharge_upbytes recharge_downbytes
1877          recharge_totalbytes );
1878   my $amount = $part_pkg->option('recharge_amount', 1); 
1879   
1880   my ($l, $v, $d) = $cust_svc->label;  # blah
1881   my $pkg = "Recharge $v"; 
1882
1883   my $bill_error = $cust_main->charge($amount, $pkg,
1884      "time: $vhash{seconds}, up: $vhash{upbytes}," . 
1885      "down: $vhash{downbytes}, total: $vhash{totalbytes}",
1886      $part_pkg->taxclass); #meh
1887
1888   my $conf = new FS::Conf;
1889   if ( $conf->exists('signup_server-realtime') && !$bill_error ) {
1890
1891     $bill_error = _do_bop_realtime( $cust_main, $status );
1892
1893     if ($bill_error) {
1894       return $bill_error;
1895     } else {
1896       my $error = $svc_x->recharge (\%vhash);
1897       return { 'error' => $error } if $error;
1898     }
1899
1900   } else {  
1901     my $error = $bill_error;
1902     $error ||= $svc_x->recharge (\%vhash);
1903     return { 'error' => $error } if $error;
1904   }
1905
1906   return { error => '', svc => $cust_svc->part_svc->svc };
1907
1908 }
1909
1910 sub _do_bop_realtime {
1911   my ($cust_main, $status) = (shift, shift);
1912
1913     my $old_balance = $cust_main->balance;
1914
1915     my $bill_error =    $cust_main->bill
1916                      || $cust_main->apply_payments_and_credits
1917                      || $cust_main->realtime_collect('selfservice' => 1);
1918
1919     if (    $cust_main->balance > $old_balance
1920          && $cust_main->balance > 0
1921          && ( $cust_main->payby !~ /^(BILL|DCRD|DCHK)$/ ?
1922               1 : $status eq 'suspended' ) ) {
1923       #this makes sense.  credit is "un-doing" the invoice
1924       my $conf = new FS::Conf;
1925       $cust_main->credit( sprintf("%.2f", $cust_main->balance - $old_balance ),
1926                           'self-service decline',
1927                           'reason_type' => $conf->config('signup_credit_type'),
1928                         );
1929       $cust_main->apply_credits( 'order' => 'newest' );
1930
1931       return { 'error' => '_decline', 'bill_error' => $bill_error };
1932     }
1933
1934     '';
1935 }
1936
1937 sub renew_info {
1938   my $p = shift;
1939
1940   my($context, $session, $custnum) = _custoragent_session_custnum($p);
1941   return { 'error' => $session } if $context eq 'error';
1942
1943   my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1944     or return { 'error' => "unknown custnum $custnum" };
1945
1946   my @cust_pkg = sort { $a->bill <=> $b->bill }
1947                  grep { $_->part_pkg->freq ne '0' }
1948                  $cust_main->ncancelled_pkgs;
1949
1950   #return { 'error' => 'No active packages to renew.' } unless @cust_pkg;
1951
1952   my $total = $cust_main->balance;
1953
1954   my @array = map {
1955                     my $bill = $_->bill;
1956                     $total += $_->part_pkg->base_recur($_, \$bill);
1957                     my $renew_date = $_->part_pkg->add_freq($_->bill);
1958                     {
1959                       'pkgnum'             => $_->pkgnum,
1960                       'amount'             => sprintf('%.2f', $total),
1961                       'bill_date'          => $_->bill,
1962                       'bill_date_pretty'   => time2str('%x', $_->bill),
1963                       'renew_date'         => $renew_date,
1964                       'renew_date_pretty'  => time2str('%x', $renew_date),
1965                       'expire_date'        => $_->expire,
1966                       'expire_date_pretty' => time2str('%x', $_->expire),
1967                     };
1968                   }
1969                   @cust_pkg;
1970
1971   return { 'dates' => \@array };
1972
1973 }
1974
1975 sub payment_info_renew_info {
1976   my $p = shift;
1977   my $renew_info   = renew_info($p);
1978   my $payment_info = payment_info($p);
1979   return { %$renew_info,
1980            %$payment_info,
1981          };
1982 }
1983
1984 sub order_renew {
1985   my $p = shift;
1986
1987   my($context, $session, $custnum) = _custoragent_session_custnum($p);
1988   return { 'error' => $session } if $context eq 'error';
1989
1990   my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1991     or return { 'error' => "unknown custnum $custnum" };
1992
1993   my $date = $p->{'date'};
1994
1995   my $now = time;
1996
1997   #freeside-daily -n -d $date fs_daily $custnum
1998   $cust_main->bill_and_collect( 'time'         => $date,
1999                                 'invoice_time' => $now,
2000                                 'actual_time'  => $now,
2001                                 'check_freq'   => '1d',
2002                               );
2003
2004   return { 'error' => '' };
2005
2006 }
2007
2008 sub suspend_pkg {
2009   my $p = shift;
2010   my $session = _cache->get($p->{'session_id'})
2011     or return { 'error' => "Can't resume session" }; #better error message
2012
2013   my $custnum = $session->{'custnum'};
2014
2015   my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
2016     or return { 'error' => "unknown custnum $custnum" };
2017
2018   my $conf = new FS::Conf;
2019   my $reasonnum = 
2020     $conf->config('selfservice-self_suspend_reason', $cust_main->agentnum)
2021       or return { 'error' => 'Permission denied' };
2022
2023   my $pkgnum = $p->{'pkgnum'};
2024
2025   my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
2026                                         'pkgnum'  => $pkgnum,   } )
2027     or return { 'error' => "unknown pkgnum $pkgnum" };
2028
2029   my $error = $cust_pkg->suspend(reason => $reasonnum);
2030   return { 'error' => $error };
2031
2032 }
2033
2034 sub cancel_pkg {
2035   my $p = shift;
2036   my $session = _cache->get($p->{'session_id'})
2037     or return { 'error' => "Can't resume session" }; #better error message
2038
2039   my $custnum = $session->{'custnum'};
2040
2041   my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
2042     or return { 'error' => "unknown custnum $custnum" };
2043
2044   my $pkgnum = $p->{'pkgnum'};
2045
2046   my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
2047                                         'pkgnum'  => $pkgnum,   } )
2048     or return { 'error' => "unknown pkgnum $pkgnum" };
2049
2050   my $error = $cust_pkg->cancel('quiet' => 1);
2051   return { 'error' => $error };
2052
2053 }
2054
2055 sub provision_phone {
2056  my $p = shift;
2057  my @bulkdid;
2058  @bulkdid = @{$p->{'bulkdid'}} if $p->{'bulkdid'};
2059
2060  if($p->{'svcnum'} && $p->{'svcnum'} =~ /^\d+$/){
2061       my($context, $session, $custnum) = _custoragent_session_custnum($p);
2062       return { 'error' => $session } if $context eq 'error';
2063     
2064       my $svc_phone = qsearchs('svc_phone', { svcnum => $p->{'svcnum'} });
2065       return { 'error' => 'service not found' } unless $svc_phone;
2066       return { 'error' => 'invalid svcnum' } 
2067         if $svc_phone && $svc_phone->cust_svc->cust_pkg->custnum != $custnum;
2068
2069       $svc_phone->email($p->{'email'}) 
2070         if $svc_phone->email ne $p->{'email'} && $p->{'email'} =~ /^([\w\.\d@]+|)$/;
2071       $svc_phone->forwarddst($p->{'forwarddst'}) 
2072         if $svc_phone->forwarddst ne $p->{'forwarddst'} 
2073             && $p->{'forwarddst'} =~ /^(\d+|)$/;
2074       return { 'error' => $svc_phone->replace };
2075  }
2076
2077 # single DID LNP
2078  unless($p->{'lnp'}) {
2079     $p->{'lnp_desired_due_date'} = parse_datetime($p->{'lnp_desired_due_date'});
2080     $p->{'lnp_status'} = "portingin";
2081     return _provision( 'FS::svc_phone',
2082                   [qw(lnp_desired_due_date lnp_other_provider 
2083                     lnp_other_provider_account phonenum countrycode lnp_status)],
2084                   [qw(phonenum countrycode)],
2085                   $p,
2086                   @_
2087                 );
2088  }
2089
2090 # single DID order
2091  unless (scalar(@bulkdid)) {
2092     return _provision( 'FS::svc_phone',
2093                   [qw(phonenum countrycode)],
2094                   [qw(phonenum countrycode)],
2095                   $p,
2096                   @_
2097                 );
2098  }
2099
2100 # bulk DID order case
2101   my $error;
2102   foreach my $did ( @bulkdid ) {
2103     $did =~ s/[^0-9]//g;
2104     $error = _provision( 'FS::svc_phone',
2105               [qw(phonenum countrycode)],
2106               [qw(phonenum countrycode)],
2107               {
2108                 'pkgnum' => $p->{'pkgnum'},
2109                 'svcpart' => $p->{'svcpart'},
2110                 'phonenum' => $did,
2111                 'countrycode' => $p->{'countrycode'},
2112                 'session_id' => $p->{'session_id'},
2113               }
2114             );
2115     return $error if ($error->{'error'} && length($error->{'error'}) > 1);
2116   }
2117   { 'bulkdid' => [ @bulkdid ], 'svc' => $error->{'svc'} }
2118 }
2119
2120 sub provision_acct {
2121   my $p = shift;
2122   warn "provision_acct called\n"
2123     if $DEBUG;
2124
2125   return { 'error' => gettext('passwords_dont_match') }
2126     if $p->{'_password'} ne $p->{'_password2'};
2127   return { 'error' => gettext('empty_password') }
2128     unless length($p->{'_password'});
2129  
2130   if ($p->{'domsvc'}) {
2131     my %domains = domain_select_hash FS::svc_acct(map { $_ => $p->{$_} }
2132                                                   qw ( svcpart pkgnum ) );
2133     return { 'error' => gettext('invalid_domain') }
2134       unless ($domains{$p->{'domsvc'}});
2135   }
2136
2137   warn "provision_acct calling _provision\n"
2138     if $DEBUG;
2139   _provision( 'FS::svc_acct',
2140               [qw(username _password domsvc)],
2141               [qw(username _password domsvc)],
2142               $p,
2143               @_
2144             );
2145 }
2146
2147 sub provision_external {
2148   my $p = shift;
2149   #_provision( 'FS::svc_external', [qw(id title)], [qw(id title)], $p, @_ );
2150   _provision( 'FS::svc_external',
2151               [],
2152               [qw(id title)],
2153               $p,
2154               @_
2155             );
2156 }
2157
2158 sub _provision {
2159   my( $class, $fields, $return_fields, $p ) = splice(@_, 0, 4);
2160   warn "_provision called for $class\n"
2161     if $DEBUG;
2162
2163   my($context, $session, $custnum) = _custoragent_session_custnum($p);
2164   return { 'error' => $session } if $context eq 'error';
2165
2166   my $search = { 'custnum' => $custnum };
2167   $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2168   my $cust_main = qsearchs('cust_main', $search )
2169     or return { 'error' => "unknown custnum $custnum" };
2170
2171   my $pkgnum = $p->{'pkgnum'};
2172
2173   warn "searching for custnum $custnum pkgnum $pkgnum\n"
2174     if $DEBUG;
2175   my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
2176                                         'pkgnum'  => $pkgnum,
2177                                                                } )
2178     or return { 'error' => "unknown pkgnum $pkgnum" };
2179
2180   warn "searching for svcpart ". $p->{'svcpart'}. "\n"
2181     if $DEBUG;
2182   my $part_svc = qsearchs('part_svc', { 'svcpart' => $p->{'svcpart'} } )
2183     or return { 'error' => "unknown svcpart $p->{'svcpart'}" };
2184
2185   warn "creating $class record\n"
2186     if $DEBUG;
2187   my $svc_x = $class->new( {
2188     'pkgnum'  => $p->{'pkgnum'},
2189     'svcpart' => $p->{'svcpart'},
2190     map { $_ => $p->{$_} } @$fields
2191   } );
2192   warn "inserting $class record\n"
2193     if $DEBUG;
2194   my $error = $svc_x->insert;
2195
2196   unless ( $error ) {
2197     warn "finding inserted record for svcnum ". $svc_x->svcnum. "\n"
2198       if $DEBUG;
2199     $svc_x = qsearchs($svc_x->table, { 'svcnum' => $svc_x->svcnum })
2200   }
2201
2202   my $return = { 'svc'   => $part_svc->svc,
2203                  'error' => $error,
2204                  map { $_ => $svc_x->get($_) } @$return_fields
2205                };
2206   warn "_provision returning ". Dumper($return). "\n"
2207     if $DEBUG;
2208   return $return;
2209
2210 }
2211
2212 sub part_svc_info {
2213   my $p = shift;
2214
2215   my($context, $session, $custnum) = _custoragent_session_custnum($p);
2216   return { 'error' => $session } if $context eq 'error';
2217
2218   my $search = { 'custnum' => $custnum };
2219   $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2220   my $cust_main = qsearchs('cust_main', $search )
2221     or return { 'error' => "unknown custnum $custnum" };
2222
2223   my $pkgnum = $p->{'pkgnum'};
2224
2225   my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
2226                                         'pkgnum'  => $pkgnum,
2227                                                                } )
2228     or return { 'error' => "unknown pkgnum $pkgnum" };
2229
2230   my $svcpart = $p->{'svcpart'};
2231
2232   my $pkg_svc = qsearchs('pkg_svc', { 'pkgpart' => $cust_pkg->pkgpart,
2233                                       'svcpart' => $svcpart,           } )
2234     or return { 'error' => "unknown svcpart $svcpart for pkgnum $pkgnum" };
2235   my $part_svc = $pkg_svc->part_svc;
2236
2237   my $conf = new FS::Conf;
2238
2239   my $ret = {
2240     'svc'     => $part_svc->svc,
2241     'svcdb'   => $part_svc->svcdb,
2242     'pkgnum'  => $pkgnum,
2243     'svcpart' => $svcpart,
2244     'custnum' => $custnum,
2245
2246     'security_phrase' => 0, #XXX !
2247     'svc_acct_pop'    => [], #XXX !
2248     'popnum'          => '',
2249     'init_popstate'   => '',
2250     'popac'           => '',
2251     'acstate'         => '',
2252
2253     'small_custview' =>
2254       small_custview( $cust_main, $conf->config('countrydefault') ),
2255
2256   };
2257
2258   if ($p->{'svcnum'} && $p->{'svcnum'} =~ /^\d+$/ 
2259                      && $ret->{'svcdb'} eq 'svc_phone') {
2260         $ret->{'svcnum'} = $p->{'svcnum'};
2261         my $svc_phone = qsearchs('svc_phone', { svcnum => $p->{'svcnum'} });
2262         if ( $svc_phone && $svc_phone->cust_svc->cust_pkg->custnum == $custnum ) {
2263             $ret->{'email'} = $svc_phone->email;
2264             $ret->{'forwarddst'} = $svc_phone->forwarddst;
2265         }
2266   }
2267
2268   $ret;
2269 }
2270
2271 sub unprovision_svc {
2272   my $p = shift;
2273
2274   my($context, $session, $custnum) = _custoragent_session_custnum($p);
2275   return { 'error' => $session } if $context eq 'error';
2276
2277   my $search = { 'custnum' => $custnum };
2278   $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2279   my $cust_main = qsearchs('cust_main', $search )
2280     or return { 'error' => "unknown custnum $custnum" };
2281
2282   my $svcnum = $p->{'svcnum'};
2283
2284   my $cust_svc = qsearchs('cust_svc', { 'svcnum'  => $svcnum, } )
2285     or return { 'error' => "unknown svcnum $svcnum" };
2286
2287   return { 'error' => "Service $svcnum does not belong to customer $custnum" }
2288     unless $cust_svc->cust_pkg->custnum == $custnum;
2289
2290   my $conf = new FS::Conf;
2291
2292   return { 'svc'   => $cust_svc->part_svc->svc,
2293            'error' => $cust_svc->cancel,
2294            'small_custview' =>
2295              small_custview( $cust_main, $conf->config('countrydefault') ),
2296          };
2297
2298 }
2299
2300 sub myaccount_passwd {
2301   my $p = shift;
2302   my($context, $session, $custnum) = _custoragent_session_custnum($p);
2303   return { 'error' => $session } if $context eq 'error';
2304
2305   return { 'error' => "New passwords don't match." }
2306     if $p->{'new_password'} ne $p->{'new_password2'};
2307
2308   return { 'error' => 'Enter new password' }
2309     unless length($p->{'new_password'});
2310
2311   #my $search = { 'custnum' => $custnum };
2312   #$search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2313   $custnum =~ /^(\d+)$/ or die "illegal custnum";
2314   my $search = " AND custnum = $1";
2315   $search .= " AND agentnum = ". $session->{'agentnum'} if $context eq 'agent';
2316
2317   my $svc_acct = qsearchs( {
2318     'table'     => 'svc_acct',
2319     'addl_from' => 'LEFT JOIN cust_svc  USING ( svcnum  ) '.
2320                    'LEFT JOIN cust_pkg  USING ( pkgnum  ) '.
2321                    'LEFT JOIN cust_main USING ( custnum ) ',
2322     'hashref'   => { 'svcnum' => $p->{'svcnum'}, },
2323     'extra_sql' => $search, #important
2324   } )
2325     or return { 'error' => "Service not found" };
2326
2327   if ( exists($p->{'old_password'}) ) {
2328     return { 'error' => "Incorrect password." }
2329       unless $svc_acct->check_password($p->{'old_password'});
2330   }
2331
2332   $svc_acct->_password($p->{'new_password'});
2333   my $error = $svc_acct->replace();
2334
2335   my($label, $value) = $svc_acct->cust_svc->label;
2336
2337   return { 'error' => $error,
2338            'label' => $label,
2339            'value' => $value,
2340          };
2341
2342 }
2343
2344 sub reset_passwd {
2345   my $p = shift;
2346
2347   my $conf = new FS::Conf;
2348   my $verification = $conf->config('selfservice-password_reset_verification')
2349     or return { 'error' => 'Password resets disabled' };
2350
2351   my $username = $p->{'username'};
2352
2353   my $svc_domain = qsearchs('svc_domain', { 'domain' => $p->{'domain'} } )
2354     or return { 'error' => 'Account not found' };
2355
2356   my $svc_acct = qsearchs('svc_acct', { 'username' => $p->{'username'},
2357                                         'domsvc'   => $svc_domain->svcnum  }
2358                          )
2359     or return { 'error' => 'Account not found' };
2360
2361   my $cust_pkg = $svc_acct->cust_svc->cust_pkg
2362     or return { 'error' => 'Account not found' };
2363
2364   my $cust_main = $cust_pkg->cust_main;
2365
2366   my %verify = (
2367     'paymask' => sub { 
2368       my( $p, $cust_main ) = @_;
2369       $cust_main->payby =~ /^(CARD|DCRD|CHEK|DCHK)$/
2370         && $p->{'paymask'} eq substr($cust_main->paymask, -4)
2371     },
2372     'amount'  => sub {
2373       my( $p, $cust_main ) = @_;
2374       my $cust_pay = qsearchs({
2375         'table' => 'cust_pay',
2376         'hashref' => { 'custnum' => $cust_main->custnum },
2377         'order_by' => 'ORDER BY _date DESC LIMIT 1',
2378       })
2379         or return 0;
2380
2381       $p->{'amount'} == $cust_pay->paid;
2382     },
2383     'zip'     => sub {
2384       my( $p, $cust_main ) = @_;
2385       $p->{'zip'} eq $cust_main->zip
2386         || ( $cust_main->ship_zip && $p->{'zip'} eq $cust_main->ship_zip );
2387     },
2388   );
2389
2390   foreach my $verify ( split(',', $verification) ) {
2391
2392     &{ $verify{$verify} }( $p, $cust_main )
2393       or return { 'error' => 'Account not found' };
2394
2395   }
2396
2397   #we're verified.  now what?
2398  
2399
2400   return { 'error' => '' };
2401 }
2402
2403
2404 sub create_ticket {
2405   my $p = shift;
2406   my($context, $session, $custnum) = _custoragent_session_custnum($p);
2407   return { 'error' => $session } if $context eq 'error';
2408
2409   warn "$me create_ticket: initializing ticket system\n" if $DEBUG;
2410   FS::TicketSystem->init();
2411
2412   my $conf = new FS::Conf;
2413   my $queue = $p->{'queue'}
2414               || $conf->config('ticket_system-selfservice_queueid')
2415               || $conf->config('ticket_system-default_queueid');
2416
2417   warn "$me create_ticket: creating ticket\n" if $DEBUG;
2418   my $err_or_ticket = FS::TicketSystem->create_ticket(
2419     '', #create RT session based on FS CurrentUser (fs_selfservice)
2420     'queue'   => $queue,
2421     'custnum' => $custnum,
2422     'svcnum'  => $session->{'svcnum'},
2423     map { $_ => $p->{$_} } qw( requestor cc subject message mime_type )
2424   );
2425
2426   if ( ref($err_or_ticket) ) {
2427     warn "$me create_ticket: successful: ". $err_or_ticket->id. "\n"
2428       if $DEBUG;
2429     return { 'error'     => '',
2430              'ticket_id' => $err_or_ticket->id,
2431            };
2432   } else {
2433     warn "$me create_ticket: unsuccessful: $err_or_ticket\n"
2434       if $DEBUG;
2435     return { 'error' => $err_or_ticket };
2436   }
2437
2438
2439 }
2440
2441 sub did_report {
2442   my $p = shift;
2443   my($context, $session, $custnum) = _custoragent_session_custnum($p);
2444   return { 'error' => $session } if $context eq 'error';
2445  
2446   return { error => 'requested format not implemented' } 
2447     unless ($p->{'format'} eq 'csv' || $p->{'format'} eq 'xls');
2448
2449   my $conf = new FS::Conf;
2450   my $age_threshold = 0;
2451   $age_threshold = time() - $conf->config('selfservice-recent-did-age')
2452     if ($p->{'recentonly'} && $conf->exists('selfservice-recent-did-age'));
2453
2454   my $search = { 'custnum' => $custnum };
2455   $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2456   my $cust_main = qsearchs('cust_main', $search )
2457     or return { 'error' => "unknown custnum $custnum" };
2458
2459 # does it make more sense to just run one sql query for this instead of all the
2460 # insanity below? would increase performance greately for large data sets?
2461   my @svc_phone = ();
2462   foreach my $cust_pkg ( $cust_main->ncancelled_pkgs ) {
2463         my @part_svc = $cust_pkg->part_svc;
2464         foreach my $part_svc ( @part_svc ) {
2465             if($part_svc->svcdb eq 'svc_phone'){
2466                 my @cust_pkg_svc = @{$part_svc->cust_pkg_svc};
2467                 foreach my $cust_pkg_svc ( @cust_pkg_svc ) {
2468                     push @svc_phone, $cust_pkg_svc->svc_x
2469                         if $cust_pkg_svc->date_inserted >= $age_threshold;
2470                 }
2471             }
2472         }
2473   }
2474
2475   my $csv;
2476   my $xls;
2477   my($xls_r,$xls_c) = (0,0);
2478   my $xls_workbook;
2479   my $content = '';
2480   my @fields = qw( countrycode phonenum pin sip_password phone_name );
2481   if($p->{'format'} eq 'csv') {
2482     $csv = new Text::CSV_XS { 'always_quote' => 1,
2483                                  'eol'          => "\n",
2484                                 };
2485     return { 'error' => 'Unable to create CSV' } unless $csv->combine(@fields);
2486     $content .= $csv->string;
2487   }
2488   elsif($p->{'format'} eq 'xls') {
2489     my $XLS1 = new IO::Scalar \$content;
2490     $xls_workbook = Spreadsheet::WriteExcel->new($XLS1) 
2491         or return { 'error' => "Error opening .xls file: $!" };
2492     $xls = $xls_workbook->add_worksheet('DIDs');
2493     foreach ( @fields ) {
2494         $xls->write(0,$xls_c++,$_);
2495     }
2496     $xls_r++;
2497   }
2498
2499   foreach my $svc_phone ( @svc_phone ) {
2500     my @cols = map { $svc_phone->$_ } @fields;
2501     if($p->{'format'} eq 'csv') {
2502         return { 'error' => 'Unable to create CSV' } 
2503             unless $csv->combine(@cols);
2504         $content .= $csv->string;
2505     }
2506     elsif($p->{'format'} eq 'xls') {
2507         $xls_c = 0;
2508         foreach ( @cols ) {
2509             $xls->write($xls_r,$xls_c++,$_);
2510         }
2511         $xls_r++;
2512     }
2513   }
2514
2515   $xls_workbook->close() if $p->{'format'} eq 'xls';
2516   
2517   { content => $content, format => $p->{'format'}, };
2518 }
2519
2520 sub get_ticket {
2521   my $p = shift;
2522   my($context, $session, $custnum) = _custoragent_session_custnum($p);
2523   return { 'error' => $session } if $context eq 'error';
2524
2525   warn "$me get_ticket: initializing ticket system\n" if $DEBUG;
2526   FS::TicketSystem->init();
2527   return { 'error' => 'get_ticket configuration error' }
2528     if $FS::TicketSystem::system ne 'RT_Internal';
2529
2530   # check existence and ownership as part of this
2531   warn "$me get_ticket: fetching ticket\n" if $DEBUG;
2532   my $rt_session = FS::TicketSystem->session('');
2533   my $Ticket = FS::TicketSystem->get_ticket_object(
2534     $rt_session, 
2535     ticket_id => $p->{'ticket_id'},
2536     custnum => $custnum
2537   );
2538   return { 'error' => 'ticket not found' } if !$Ticket;
2539
2540   if ( length( $p->{'subject'} || '' ) ) {
2541     # subject change
2542     if ( $p->{'subject'} ne $Ticket->Subject ) {
2543       my ($val, $msg) = $Ticket->SetSubject($p->{'subject'});
2544       return { 'error' => "unable to set subject: $msg" } if !$val;
2545     }
2546   }
2547
2548   if(length($p->{'reply'})) {
2549     my @err_or_res = FS::TicketSystem->correspond_ticket(
2550       $rt_session,
2551       'ticket_id' => $p->{'ticket_id'},
2552       'content' => $p->{'reply'},
2553     );
2554
2555     return { 'error' => 'unable to reply to ticket' } 
2556     unless ( $err_or_res[0] != 0 && defined $err_or_res[2] );
2557   }
2558
2559   warn "$me get_ticket: getting ticket history\n" if $DEBUG;
2560   my $err_or_ticket = FS::TicketSystem->get_ticket(
2561     $rt_session,
2562     'ticket_id' => $p->{'ticket_id'},
2563   );
2564
2565   if ( !ref($err_or_ticket) ) { # there is no way this should ever happen
2566     warn "$me get_ticket: unsuccessful: $err_or_ticket\n"
2567       if $DEBUG;
2568     return { 'error' => $err_or_ticket };
2569   }
2570
2571   my @custs = @{$err_or_ticket->{'custs'}};
2572   my @txns = @{$err_or_ticket->{'txns'}};
2573   my @filtered_txns;
2574
2575   # superseded by check in get_ticket_object
2576   #return { 'error' => 'invalid ticket requested' } 
2577   #unless grep($_ eq $custnum, @custs);
2578
2579   foreach my $txn ( @txns ) {
2580     push @filtered_txns, $txn 
2581     if ($txn->{'type'} eq 'EmailRecord' 
2582       || $txn->{'type'} eq 'Correspond'
2583       || $txn->{'type'} eq 'Create');
2584   }
2585
2586   warn "$me get_ticket: successful: \n"
2587   if $DEBUG;
2588   return { 'error'     => '',
2589     'transactions' => \@filtered_txns,
2590     'ticket_fields' => $err_or_ticket->{'fields'},
2591     'ticket_id' => $p->{'ticket_id'},
2592   };
2593 }
2594
2595 sub adjust_ticket_priority {
2596   my $p = shift;
2597   my($context, $session, $custnum) = _custoragent_session_custnum($p);
2598   return { 'error' => $session } if $context eq 'error';
2599
2600   warn "$me adjust_ticket_priority: initializing ticket system\n" if $DEBUG;
2601   FS::TicketSystem->init;
2602   my $ss_priority = FS::TicketSystem->selfservice_priority;
2603
2604   return { 'error' => 'adjust_ticket_priority configuration error' }
2605     if $FS::TicketSystem::system ne 'RT_Internal'
2606       or !$ss_priority;
2607
2608   my $values = $p->{'values'}; #hashref, id => priority value
2609   my %ticket_error;
2610
2611   foreach my $id (keys %$values) {
2612     warn "$me adjust_ticket_priority: fetching ticket $id\n" if $DEBUG;
2613     my $Ticket = FS::TicketSystem->get_ticket_object('',
2614       'ticket_id' => $id,
2615       'custnum'   => $custnum,
2616     );
2617     if ( !$Ticket ) {
2618       $ticket_error{$id} = 'ticket not found';
2619       next;
2620     }
2621     
2622   # RT API stuff--would we gain anything by wrapping this in FS::TicketSystem?
2623   # We're not going to implement it for RT_External.
2624     my $old_value = $Ticket->FirstCustomFieldValue($ss_priority);
2625     my $new_value = $values->{$id};
2626     next if $old_value eq $new_value;
2627
2628     warn "$me adjust_ticket_priority: updating ticket $id\n" if $DEBUG;
2629
2630     # AddCustomFieldValue works fine (replacing any existing value) if it's 
2631     # a single-valued custom field, which it should be.  If it's not, you're 
2632     # doing something wrong.
2633     my ($val, $msg);
2634     if ( length($new_value) ) {
2635       ($val, $msg) = $Ticket->AddCustomFieldValue( 
2636         Field => $ss_priority,
2637         Value => $new_value,
2638       );
2639     }
2640     else {
2641       ($val, $msg) = $Ticket->DeleteCustomFieldValue(
2642         Field => $ss_priority,
2643         Value => $old_value,
2644       );
2645     }
2646
2647     $ticket_error{$id} = $msg if !$val;
2648     warn "$me adjust_ticket_priority: $id: $msg\n" if $DEBUG and !$val;
2649   }
2650   return { 'error' => '',
2651            'ticket_error' => \%ticket_error,
2652            %{ customer_info($p) } # send updated customer info back
2653          }
2654 }
2655
2656 #--
2657
2658 sub _custoragent_session_custnum {
2659   my $p = shift;
2660
2661   my($context, $session, $custnum);
2662   if ( $p->{'session_id'} ) {
2663
2664     $context = 'customer';
2665     $session = _cache->get($p->{'session_id'})
2666       or return ( 'error' => "Can't resume session" ); #better error message
2667     $custnum = $session->{'custnum'};
2668
2669   } elsif ( $p->{'agent_session_id'} ) {
2670
2671     $context = 'agent';
2672     my $agent_cache = new FS::ClientAPI_SessionCache( {
2673       'namespace' => 'FS::ClientAPI::Agent',
2674     } );
2675     $session = $agent_cache->get($p->{'agent_session_id'})
2676       or return ( 'error' => "Can't resume session" ); #better error message
2677     $custnum = $p->{'custnum'};
2678
2679   } else {
2680     $context = 'error';
2681     return ( 'error' => "Can't resume session" ); #better error message
2682   }
2683
2684   ($context, $session, $custnum);
2685
2686 }
2687
2688 1;
2689