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