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