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