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