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