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