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