e41fe7d565f29361f9456553ef9b926f068f1759
[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 Data::Dumper;
8 use Digest::MD5 qw(md5_hex);
9 use Date::Format;
10 use Business::CreditCard;
11 use Time::Duration;
12 use Time::Local qw(timelocal_nocheck);
13 use FS::UI::Web::small_custview qw(small_custview); #less doh
14 use FS::UI::Web;
15 use FS::UI::bytecount qw( display_bytecount );
16 use FS::Conf;
17 #use FS::UID qw(dbh);
18 use FS::Record qw(qsearch qsearchs dbh);
19 use FS::Msgcat qw(gettext);
20 use FS::Misc qw(card_types);
21 use FS::ClientAPI_SessionCache;
22 use FS::svc_acct;
23 use FS::svc_domain;
24 use FS::svc_phone;
25 use FS::svc_external;
26 use FS::part_svc;
27 use FS::cust_main;
28 use FS::cust_bill;
29 use FS::cust_main_county;
30 use FS::cust_pkg;
31 use FS::payby;
32 use FS::acct_rt_transaction;
33 use HTML::Entities;
34 use FS::TicketSystem;
35 use Text::CSV_XS;
36 use IO::Scalar;
37 use Spreadsheet::WriteExcel;
38
39 $DEBUG = 0;
40 $me = '[FS::ClientAPI::MyAccount]';
41
42 use vars qw( @cust_main_editable_fields );
43 @cust_main_editable_fields = qw(
44   first last company address1 address2 city
45     county state zip country daytime night fax
46   ship_first ship_last ship_company ship_address1 ship_address2 ship_city
47     ship_state ship_zip ship_country ship_daytime ship_night ship_fax
48   payby payinfo payname paystart_month paystart_year payissue payip
49   ss paytype paystate stateid stateid_state
50 );
51
52 sub _cache {
53   $cache ||= new FS::ClientAPI_SessionCache( {
54                'namespace' => 'FS::ClientAPI::MyAccount',
55              } );
56 }
57
58 sub skin_info {
59   my $p = shift;
60
61   my($context, $session, $custnum) = _custoragent_session_custnum($p);
62   #return { 'error' => $session } if $context eq 'error';
63
64   my $agentnum = '';
65   if ( $context eq 'customer' ) {
66
67     my $sth = dbh->prepare('SELECT agentnum FROM cust_main WHERE custnum = ?')
68       or die dbh->errstr;
69
70     $sth->execute($custnum) or die $sth->errstr;
71
72     $agentnum = $sth->fetchrow_arrayref->[0]
73       or die "no agentnum for custnum $custnum";
74
75   #} elsif ( $context eq 'agent' ) {
76   } elsif ( $p->{'agentnum'} =~ /^(\d+)$/ ) {
77     $agentnum = $1;
78   }
79
80   my $conf = new FS::Conf;
81
82   #false laziness w/Signup.pm
83
84   my $skin_info_cache_agent = _cache->get("skin_info_cache_agent$agentnum");
85
86   if ( $skin_info_cache_agent ) {
87
88     warn "$me loading cached skin info for agentnum $agentnum\n"
89       if $DEBUG > 1;
90
91   } else {
92
93     warn "$me populating skin info cache for agentnum $agentnum\n"
94       if $DEBUG > 1;
95
96     $skin_info_cache_agent = {
97       'agentnum' => $agentnum,
98       ( map { $_ => scalar( $conf->config($_, $agentnum) ) }
99         qw( company_name ) ),
100       ( map { $_ => scalar( $conf->config("selfservice-$_", $agentnum ) ) }
101         qw( body_bgcolor box_bgcolor
102             text_color link_color vlink_color hlink_color alink_color
103             font title_color title_align title_size menu_bgcolor menu_fontsize
104           )
105       ),
106       ( map { $_ => $conf->exists("selfservice-$_", $agentnum ) }
107         qw( menu_skipblanks menu_skipheadings menu_nounderline )
108       ),
109       ( map { $_ => scalar($conf->config_binary("selfservice-$_", $agentnum)) }
110         qw( title_left_image title_right_image
111             menu_top_image menu_body_image menu_bottom_image
112           )
113       ),
114       'logo' => scalar($conf->config_binary('logo.png', $agentnum )),
115       ( map { $_ => join("\n", $conf->config("selfservice-$_", $agentnum ) ) }
116         qw( head body_header body_footer company_address ) ),
117     };
118
119     _cache->set("skin_info_cache_agent$agentnum", $skin_info_cache_agent);
120
121   }
122
123   #{ %$skin_info_cache_agent };
124   $skin_info_cache_agent;
125
126 }
127
128 sub login_info {
129   my $p = shift;
130
131   my $conf = new FS::Conf;
132
133   my %info = (
134     %{ skin_info($p) },
135     'phone_login'  => $conf->exists('selfservice_server-phone_login'),
136     'single_domain'=> scalar($conf->config('selfservice_server-single_domain')),
137   );
138
139   return \%info;
140
141 }
142
143 #false laziness w/FS::ClientAPI::passwd::passwd
144 sub login {
145   my $p = shift;
146
147   my $conf = new FS::Conf;
148
149   my $svc_x = '';
150   if ( $p->{'domain'} eq 'svc_phone'
151        && $conf->exists('selfservice_server-phone_login') ) { 
152
153     my $svc_phone = qsearchs( 'svc_phone', { 'phonenum' => $p->{'username'} } );
154     return { error => 'Number not found.' } unless $svc_phone;
155
156     #XXX?
157     #my $pkg_svc = $svc_acct->cust_svc->pkg_svc;
158     #return { error => 'Only primary user may log in.' } 
159     #  if $conf->exists('selfservice_server-primary_only')
160     #    && ( ! $pkg_svc || $pkg_svc->primary_svc ne 'Y' );
161
162     return { error => 'Incorrect PIN.' }
163       unless $svc_phone->check_pin($p->{'password'});
164
165     $svc_x = $svc_phone;
166
167   } else {
168
169     my $svc_domain = qsearchs('svc_domain', { 'domain' => $p->{'domain'} } )
170       or return { error => 'Domain '. $p->{'domain'}. ' not found' };
171
172     my $svc_acct = qsearchs( 'svc_acct', { 'username'  => $p->{'username'},
173                                            'domsvc'    => $svc_domain->svcnum, }
174                            );
175     return { error => 'User not found.' } unless $svc_acct;
176
177     if($conf->exists('selfservice_server-login_svcpart')) {
178         my @svcpart = $conf->config('selfservice_server-login_svcpart');
179         my $svcpart = $svc_acct->cust_svc->svcpart;
180         return { error => 'Invalid user.' } 
181             unless grep($_ eq $svcpart, @svcpart);
182     }
183
184     return { error => 'Incorrect password.' }
185       unless $svc_acct->check_password($p->{'password'});
186
187     $svc_x = $svc_acct;
188
189   }
190
191   my $session = {
192     'svcnum' => $svc_x->svcnum,
193   };
194
195   my $cust_svc = $svc_x->cust_svc;
196   my $cust_pkg = $cust_svc->cust_pkg;
197   if ( $cust_pkg ) {
198     my $cust_main = $cust_pkg->cust_main;
199     $session->{'custnum'} = $cust_main->custnum;
200     if ( $conf->exists('pkg-balances') ) {
201       my @cust_pkg = grep { $_->part_pkg->freq !~ /^(0|$)/ }
202                           $cust_main->ncancelled_pkgs;
203       $session->{'pkgnum'} = $cust_pkg->pkgnum
204         if scalar(@cust_pkg) > 1;
205     }
206   }
207
208   #my $pkg_svc = $svc_acct->cust_svc->pkg_svc;
209   #return { error => 'Only primary user may log in.' } 
210   #  if $conf->exists('selfservice_server-primary_only')
211   #    && ( ! $pkg_svc || $pkg_svc->primary_svc ne 'Y' );
212   my $part_pkg = $cust_pkg->part_pkg;
213   return { error => 'Only primary user may log in.' }
214     if $conf->exists('selfservice_server-primary_only')
215        && $cust_svc->svcpart != $part_pkg->svcpart([qw( svc_acct svc_phone )]);
216
217   my $session_id;
218   do {
219     $session_id = md5_hex(md5_hex(time(). {}. rand(). $$))
220   } until ( ! defined _cache->get($session_id) ); #just in case
221
222   my $timeout = $conf->config('selfservice-session_timeout') || '1 hour';
223   _cache->set( $session_id, $session, $timeout );
224
225   return { 'error'      => '',
226            'session_id' => $session_id,
227          };
228 }
229
230 sub logout {
231   my $p = shift;
232   if ( $p->{'session_id'} ) {
233     _cache->remove($p->{'session_id'});
234     return { %{ skin_info($p) }, 'error' => '' };
235   } else {
236     return { %{ skin_info($p) }, 'error' => "Can't resume session" }; #better error message
237   }
238 }
239
240 sub access_info {
241   my $p = shift;
242
243   my $conf = new FS::Conf;
244
245   my $info = skin_info($p);
246
247   use vars qw( $cust_paybys ); #cache for performance
248   unless ( $cust_paybys ) {
249
250     my %cust_paybys = map { $_ => 1 }
251                       map { FS::payby->payby2payment($_) }
252                           $conf->config('signup_server-payby');
253
254     $cust_paybys = [ keys %cust_paybys ];
255
256   }
257   $info->{'cust_paybys'} = $cust_paybys;
258
259   my($context, $session, $custnum) = _custoragent_session_custnum($p);
260   return { 'error' => $session } if $context eq 'error';
261
262   my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
263     or return { 'error' => "unknown custnum $custnum" };
264
265   $info->{hide_payment_fields} =
266   [
267     map { my $pg = '';
268           if ( FS::payby->realtime($_) ) {
269             $pg = $cust_main->agent->payment_gateway(
270               'method'  => FS::payby->payby2bop($_),
271               'nofatal' => 1,
272             );
273           }
274           $pg && $pg->gateway_namespace eq 'Business::OnlineThirdPartyPayment';
275         }
276     @{ $info->{cust_paybys} }
277   ];
278
279   $info->{'self_suspend_reason'} = 
280       $conf->config('selfservice-self_suspend_reason', $cust_main->agentnum);
281
282   return { %$info,
283            'custnum'       => $custnum,
284            'access_pkgnum' => $session->{'pkgnum'},
285            'access_svcnum' => $session->{'svcnum'},
286          };
287 }
288
289 sub customer_info {
290   my $p = shift;
291
292   my($context, $session, $custnum) = _custoragent_session_custnum($p);
293   return { 'error' => $session } if $context eq 'error';
294
295   my %return;
296
297   my $conf = new FS::Conf;
298   if ($conf->exists('cust_main-require_address2')) {
299     $return{'require_address2'} = '1';
300   }else{
301     $return{'require_address2'} = '';
302   }
303   
304   if ( $custnum ) { #customer record
305
306     my $search = { 'custnum' => $custnum };
307     $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
308     my $cust_main = qsearchs('cust_main', $search )
309       or return { 'error' => "unknown custnum $custnum" };
310
311     if ( $session->{'pkgnum'} ) { 
312       $return{balance} = $cust_main->balance_pkgnum( $session->{'pkgnum'} );
313     } else {
314       $return{balance} = $cust_main->balance;
315     }
316
317     $return{tickets} = [ ($cust_main->tickets) ];
318
319     unless ( $session->{'pkgnum'} ) {
320       my @open = map {
321                        {
322                          invnum => $_->invnum,
323                          date   => time2str("%b %o, %Y", $_->_date),
324                          owed   => $_->owed,
325                        };
326                      } $cust_main->open_cust_bill;
327       $return{open_invoices} = \@open;
328     }
329
330     $return{small_custview} =
331       small_custview( $cust_main,
332                       scalar($conf->config('countrydefault')),
333                       ( $session->{'pkgnum'} ? 1 : 0 ), #nobalance
334                     );
335
336     $return{name} = $cust_main->first. ' '. $cust_main->get('last');
337
338     for (@cust_main_editable_fields) {
339       $return{$_} = $cust_main->get($_);
340     }
341
342     if ( $cust_main->payby =~ /^(CARD|DCRD)$/ ) {
343       $return{payinfo} = $cust_main->paymask;
344       @return{'month', 'year'} = $cust_main->paydate_monthyear;
345     }
346
347     $return{'invoicing_list'} =
348       join(', ', grep { $_ !~ /^(POST|FAX)$/ } $cust_main->invoicing_list );
349     $return{'postal_invoicing'} =
350       0 < ( grep { $_ eq 'POST' } $cust_main->invoicing_list );
351
352     if (scalar($conf->config('support_packages'))) {
353       my @support_services = ();
354       foreach ($cust_main->support_services) {
355         my $seconds = $_->svc_x->seconds;
356         my $time_remaining = (($seconds < 0) ? '-' : '' ).
357                              int(abs($seconds)/3600)."h".
358                              sprintf("%02d",(abs($seconds)%3600)/60)."m";
359         my $cust_pkg = $_->cust_pkg;
360         my $pkgnum = '';
361         my $pkg = '';
362         $pkgnum = $cust_pkg->pkgnum if $cust_pkg;
363         $pkg = $cust_pkg->part_pkg->pkg if $cust_pkg;
364         push @support_services, { svcnum => $_->svcnum,
365                                   time => $time_remaining,
366                                   pkgnum => $pkgnum,
367                                   pkg => $pkg,
368                                 };
369       }
370       $return{support_services} = \@support_services;
371     }
372
373     if ( $conf->config('prepayment_discounts-credit_type') ) {
374       #need to eval?
375       $return{discount_terms_hash} = { $cust_main->discount_terms_hash };
376     }
377
378   } elsif ( $session->{'svcnum'} ) { #no customer record
379
380     my $svc_acct = qsearchs('svc_acct', { 'svcnum' => $session->{'svcnum'} } )
381       or die "unknown svcnum";
382     $return{name} = $svc_acct->email;
383
384   } else {
385
386     return { 'error' => 'Expired session' }; #XXX redirect to login w/this err!
387
388   }
389
390   return { 'error'          => '',
391            'custnum'        => $custnum,
392            %return,
393          };
394
395 }
396
397 sub edit_info {
398   my $p = shift;
399   my $session = _cache->get($p->{'session_id'})
400     or return { 'error' => "Can't resume session" }; #better error message
401
402   my $custnum = $session->{'custnum'}
403     or return { 'error' => "no customer record" };
404
405   my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
406     or return { 'error' => "unknown custnum $custnum" };
407
408   my $new = new FS::cust_main { $cust_main->hash };
409   $new->set( $_ => $p->{$_} )
410     foreach grep { exists $p->{$_} } @cust_main_editable_fields;
411
412   my $payby = '';
413   if (exists($p->{'payby'})) {
414     $p->{'payby'} =~ /^([A-Z]{4})$/
415       or return { 'error' => "illegal_payby " . $p->{'payby'} };
416     $payby = $1;
417   }
418
419   if ( $payby =~ /^(CARD|DCRD)$/ ) {
420
421     $new->paydate($p->{'year'}. '-'. $p->{'month'}. '-01');
422
423     if ( $new->payinfo eq $cust_main->paymask ) {
424       $new->payinfo($cust_main->payinfo);
425     } else {
426       $new->payinfo($p->{'payinfo'});
427     }
428
429     $new->set( 'payby' => $p->{'auto'} ? 'CARD' : 'DCRD' );
430
431   } elsif ( $payby =~ /^(CHEK|DCHK)$/ ) {
432
433     my $payinfo;
434     $p->{'payinfo1'} =~ /^([\dx]+)$/
435       or return { 'error' => "illegal account number ". $p->{'payinfo1'} };
436     my $payinfo1 = $1;
437      $p->{'payinfo2'} =~ /^([\dx]+)$/
438       or return { 'error' => "illegal ABA/routing number ". $p->{'payinfo2'} };
439     my $payinfo2 = $1;
440     $payinfo = $payinfo1. '@'. $payinfo2;
441
442     $new->payinfo( ($payinfo eq $cust_main->paymask)
443                      ? $cust_main->payinfo
444                      : $payinfo
445                  );
446
447     $new->set( 'payby' => $p->{'auto'} ? 'CHEK' : 'DCHK' );
448
449   } elsif ( $payby =~ /^(BILL)$/ ) {
450     #no-op
451   } elsif ( $payby ) {  #notyet ready
452     return { 'error' => "unknown payby $payby" };
453   }
454
455   my @invoicing_list;
456   if ( exists $p->{'invoicing_list'} || exists $p->{'postal_invoicing'} ) {
457     #false laziness with httemplate/edit/process/cust_main.cgi
458     @invoicing_list = split( /\s*\,\s*/, $p->{'invoicing_list'} );
459     push @invoicing_list, 'POST' if $p->{'postal_invoicing'};
460   } else {
461     @invoicing_list = $cust_main->invoicing_list;
462   }
463
464   my $error = $new->replace($cust_main, \@invoicing_list);
465   return { 'error' => $error } if $error;
466   #$cust_main = $new;
467   
468   return { 'error' => '' };
469 }
470
471 sub payment_info {
472   my $p = shift;
473   my $session = _cache->get($p->{'session_id'})
474     or return { 'error' => "Can't resume session" }; #better error message
475
476   ##
477   #generic
478   ##
479
480   my $conf = new FS::Conf;
481   use vars qw($payment_info); #cache for performance
482   unless ( $payment_info ) {
483
484     my %states = map { $_->state => 1 }
485                    qsearch('cust_main_county', {
486                      'country' => $conf->config('countrydefault') || 'US'
487                    } );
488
489     my %cust_paybys = map { $_ => 1 }
490                       map { FS::payby->payby2payment($_) }
491                           $conf->config('signup_server-payby');
492
493     my @cust_paybys = keys %cust_paybys;
494
495     $payment_info = {
496
497       #list all counties/states/countries
498       'cust_main_county' => 
499         [ map { $_->hashref } qsearch('cust_main_county', {}) ],
500
501       #shortcut for one-country folks
502       'states' =>
503         [ sort { $a cmp $b } keys %states ],
504
505       'card_types' => card_types(),
506
507       'paytypes' => [ @FS::cust_main::paytypes ],
508
509       'paybys' => [ $conf->config('signup_server-payby') ],
510       'cust_paybys' => \@cust_paybys,
511
512       'stateid_label' => FS::Msgcat::_gettext('stateid'),
513       'stateid_state_label' => FS::Msgcat::_gettext('stateid_state'),
514
515       'show_ss'  => $conf->exists('show_ss'),
516       'show_stateid' => $conf->exists('show_stateid'),
517       'show_paystate' => $conf->exists('show_bankstate'),
518
519       'save_unchecked' => $conf->exists('selfservice-save_unchecked'),
520     };
521
522   }
523
524   ##
525   #customer-specific
526   ##
527
528   my %return = %$payment_info;
529
530   my $custnum = $session->{'custnum'};
531
532   my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
533     or return { 'error' => "unknown custnum $custnum" };
534
535   $return{hide_payment_fields} =
536   [
537     map { my $pg = '';
538           if ( FS::payby->realtime($_) ) {
539             $pg = $cust_main->agent->payment_gateway(
540               'method'  => FS::payby->payby2bop($_),
541               'nofatal' => 1,
542             );
543           }
544           $pg && $pg->gateway_namespace eq 'Business::OnlineThirdPartyPayment';
545         }
546     @{ $return{cust_paybys} }
547   ];
548
549   $return{balance} = $cust_main->balance; #XXX pkg-balances?
550
551   $return{payname} = $cust_main->payname
552                      || ( $cust_main->first. ' '. $cust_main->get('last') );
553
554   $return{$_} = $cust_main->get($_) for qw(address1 address2 city state zip);
555
556   $return{payby} = $cust_main->payby;
557   $return{stateid_state} = $cust_main->stateid_state;
558
559   if ( $cust_main->payby =~ /^(CARD|DCRD)$/ ) {
560     $return{card_type} = cardtype($cust_main->payinfo);
561     $return{payinfo} = $cust_main->paymask;
562
563     @return{'month', 'year'} = $cust_main->paydate_monthyear;
564
565   }
566
567   if ( $cust_main->payby =~ /^(CHEK|DCHK)$/ ) {
568     my ($payinfo1, $payinfo2) = split '@', $cust_main->paymask;
569     $return{payinfo1} = $payinfo1;
570     $return{payinfo2} = $payinfo2;
571     $return{paytype}  = $cust_main->paytype;
572     $return{paystate} = $cust_main->paystate;
573
574   }
575
576   if ( $conf->config('prepayment_discounts-credit_type') ) {
577     #need to eval?
578     $return{discount_terms_hash} = { $cust_main->discount_terms_hash };
579   }
580
581   #doubleclick protection
582   my $_date = time;
583   $return{paybatch} = "webui-MyAccount-$_date-$$-". rand() * 2**32;
584
585   return { 'error' => '',
586            %return,
587          };
588
589 };
590
591 #some false laziness with httemplate/process/payment.cgi - look there for
592 #ACH and CVV support stuff
593 sub process_payment {
594
595   my $p = shift;
596
597   my $session = _cache->get($p->{'session_id'})
598     or return { 'error' => "Can't resume session" }; #better error message
599
600   my %return;
601
602   my $custnum = $session->{'custnum'};
603
604   my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
605     or return { 'error' => "unknown custnum $custnum" };
606
607   $p->{'amount'} =~ /^\s*(\d+(\.\d{2})?)\s*$/
608     or return { 'error' => gettext('illegal_amount') };
609   my $amount = $1;
610   return { error => 'Amount must be greater than 0' } unless $amount > 0;
611
612   $p->{'discount_term'} =~ /^\s*(\d*)\s*$/
613     or return { 'error' => gettext('illegal_discount_term'). ': '. $p->{'discount_term'} };
614   my $discount_term = $1;
615
616   $p->{'payname'} =~ /^([\w \,\.\-\']+)$/
617     or return { 'error' => gettext('illegal_name'). " payname: ". $p->{'payname'} };
618   my $payname = $1;
619
620   $p->{'paybatch'} =~ /^([\w \!\@\#\$\%\&\(\)\-\+\;\:\'\"\,\.\?\/\=]*)$/
621     or return { 'error' => gettext('illegal_text'). " paybatch: ". $p->{'paybatch'} };
622   my $paybatch = $1;
623
624   $p->{'payby'} ||= 'CARD';
625   $p->{'payby'} =~ /^([A-Z]{4})$/
626     or return { 'error' => "illegal_payby " . $p->{'payby'} };
627   my $payby = $1;
628
629   #false laziness w/process/payment.cgi
630   my $payinfo;
631   my $paycvv = '';
632   if ( $payby eq 'CHEK' || $payby eq 'DCHK' ) {
633   
634     $p->{'payinfo1'} =~ /^([\dx]+)$/
635       or return { 'error' => "illegal account number ". $p->{'payinfo1'} };
636     my $payinfo1 = $1;
637      $p->{'payinfo2'} =~ /^([\dx]+)$/
638       or return { 'error' => "illegal ABA/routing number ". $p->{'payinfo2'} };
639     my $payinfo2 = $1;
640     $payinfo = $payinfo1. '@'. $payinfo2;
641
642     $payinfo = $cust_main->payinfo
643       if $cust_main->paymask eq $payinfo;
644    
645   } elsif ( $payby eq 'CARD' || $payby eq 'DCRD' ) {
646    
647     $payinfo = $p->{'payinfo'};
648
649     #more intelligent mathing will be needed here if you change
650     #card_masking_method and don't remove existing paymasks
651     $payinfo = $cust_main->payinfo
652       if $cust_main->paymask eq $payinfo;
653
654     $payinfo =~ s/\D//g;
655     $payinfo =~ /^(\d{13,16})$/
656       or return { 'error' => gettext('invalid_card') }; # . ": ". $self->payinfo
657     $payinfo = $1;
658
659     validate($payinfo)
660       or return { 'error' => gettext('invalid_card') }; # . ": ". $self->payinfo
661     return { 'error' => gettext('unknown_card_type') }
662       if $payinfo !~ /^99\d{14}$/ && cardtype($payinfo) eq "Unknown";
663
664     if ( length($p->{'paycvv'}) && $p->{'paycvv'} !~ /^\s*$/ ) {
665       if ( cardtype($payinfo) eq 'American Express card' ) {
666         $p->{'paycvv'} =~ /^\s*(\d{4})\s*$/
667           or return { 'error' => "CVV2 (CID) for American Express cards is four digits." };
668         $paycvv = $1;
669       } else {
670         $p->{'paycvv'} =~ /^\s*(\d{3})\s*$/
671           or return { 'error' => "CVV2 (CVC2/CID) is three digits." };
672         $paycvv = $1;
673       }
674     }
675   
676   } else {
677     die "unknown payby $payby";
678   }
679
680   my %payby2fields = (
681     'CARD' => [ qw( paystart_month paystart_year payissue payip
682                     address1 address2 city state zip country    ) ],
683     'CHEK' => [ qw( ss paytype paystate stateid stateid_state payip ) ],
684   );
685
686   my $error = $cust_main->realtime_bop( $FS::payby::payby2bop{$payby}, $amount,
687     'quiet'    => 1,
688     'payinfo'  => $payinfo,
689     'paydate'  => $p->{'year'}. '-'. $p->{'month'}. '-01',
690     'payname'  => $payname,
691     'paybatch' => $paybatch, #this doesn't actually do anything
692     'paycvv'   => $paycvv,
693     'pkgnum'   => $session->{'pkgnum'},
694     'discount_term' => $discount_term,
695     map { $_ => $p->{$_} } @{ $payby2fields{$payby} }
696   );
697   return { 'error' => $error } if $error;
698
699   $cust_main->apply_payments;
700
701   if ( $p->{'save'} ) {
702     my $new = new FS::cust_main { $cust_main->hash };
703     if ($payby eq 'CARD' || $payby eq 'DCRD') {
704       $new->set( $_ => $p->{$_} )
705         foreach qw( payname paystart_month paystart_year payissue payip
706                     address1 address2 city state zip country );
707       $new->set( 'payby' => $p->{'auto'} ? 'CARD' : 'DCRD' );
708     } elsif ($payby eq 'CHEK' || $payby eq 'DCHK') {
709       $new->set( $_ => $p->{$_} )
710         foreach qw( payname payip paytype paystate
711                     stateid stateid_state );
712       $new->set( 'payby' => $p->{'auto'} ? 'CHEK' : 'DCHK' );
713     }
714     $new->set( 'payinfo' => $cust_main->card_token || $payinfo );
715     $new->set( 'paydate' => $p->{'year'}. '-'. $p->{'month'}. '-01' );
716     my $error = $new->replace($cust_main);
717     if ( $error ) {
718       #no, this causes customers to process their payments again
719       #return { 'error' => $error };
720       #XXX just warn verosely for now so i can figure out how these happen in
721       # the first place, eventually should redirect them to the "change
722       #address" page but indicate the payment did process??
723       delete($p->{'payinfo'}); #don't want to log this!
724       warn "WARNING: error changing customer info when processing payment (not returning to customer as a processing error): $error\n".
725            "NEW: ". Dumper($new)."\n".
726            "OLD: ". Dumper($cust_main)."\n".
727            "PACKET: ". Dumper($p)."\n";
728     #} else {
729       #not needed...
730       #$cust_main = $new;
731     }
732   }
733
734   return { 'error' => '' };
735
736 }
737
738 sub realtime_collect {
739   my $p = shift;
740
741   my $session = _cache->get($p->{'session_id'})
742     or return { 'error' => "Can't resume session" }; #better error message
743
744   my $custnum = $session->{'custnum'};
745
746   my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
747     or return { 'error' => "unknown custnum $custnum" };
748
749   my $error = $cust_main->realtime_collect(
750     'method'     => $p->{'method'},
751     'pkgnum'     => $session->{'pkgnum'},
752     'session_id' => $p->{'session_id'},
753     'apply'      => 1,
754   );
755   return { 'error' => $error } unless ref( $error );
756
757   my $amount = $session->{'pkgnum'}
758                  ? $cust_main->balance_pkgnum( $session->{'pkgnum'} )
759                  : $cust_main->balance;
760
761   return { 'error' => '', amount => $amount, %$error };
762 }
763
764 sub process_payment_order_pkg {
765   my $p = shift;
766
767   my $hr = process_payment($p);
768   return $hr if $hr->{'error'};
769
770   order_pkg($p);
771 }
772
773 sub process_payment_order_renew {
774   my $p = shift;
775
776   my $hr = process_payment($p);
777   return $hr if $hr->{'error'};
778
779   order_renew($p);
780 }
781
782 sub process_prepay {
783
784   my $p = shift;
785
786   my $session = _cache->get($p->{'session_id'})
787     or return { 'error' => "Can't resume session" }; #better error message
788
789   my %return;
790
791   my $custnum = $session->{'custnum'};
792
793   my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
794     or return { 'error' => "unknown custnum $custnum" };
795
796   my( $amount, $seconds, $upbytes, $downbytes, $totalbytes ) = ( 0, 0, 0, 0, 0 );
797   my $error = $cust_main->recharge_prepay( $p->{'prepaid_cardnum'},
798                                            \$amount,
799                                            \$seconds,
800                                            \$upbytes,
801                                            \$downbytes,
802                                            \$totalbytes,
803                                          );
804
805   return { 'error' => $error } if $error;
806
807   return { 'error'     => '',
808            'amount'    => $amount,
809            'seconds'   => $seconds,
810            'duration'  => duration_exact($seconds),
811            'upbytes'   => $upbytes,
812            'upload'    => FS::UI::bytecount::bytecount_unexact($upbytes),
813            'downbytes' => $downbytes,
814            'download'  => FS::UI::bytecount::bytecount_unexact($downbytes),
815            'totalbytes'=> $totalbytes,
816            'totalload' => FS::UI::bytecount::bytecount_unexact($totalbytes),
817          };
818
819 }
820
821 sub invoice {
822   my $p = shift;
823   my $session = _cache->get($p->{'session_id'})
824     or return { 'error' => "Can't resume session" }; #better error message
825
826   my $custnum = $session->{'custnum'};
827
828   my $invnum = $p->{'invnum'};
829
830   my $cust_bill = qsearchs('cust_bill', { 'invnum'  => $invnum,
831                                           'custnum' => $custnum } )
832     or return { 'error' => "Can't find invnum" };
833
834   #my %return;
835
836   return { 'error'        => '',
837            'invnum'       => $invnum,
838            'invoice_text' => join('', $cust_bill->print_text ),
839            'invoice_html' => $cust_bill->print_html( { unsquelch_cdr => 1 } ),
840          };
841
842 }
843
844 sub invoice_logo {
845   my $p = shift;
846
847   #sessioning for this?  how do we get the session id to the backend invoice
848   # template so it can add it to the link, blah
849
850   my $agentnum = '';
851   if ( $p->{'invnum'} ) {
852     my $cust_bill = qsearchs('cust_bill', { 'invnum' => $p->{'invnum'} } )
853       or return { 'error' => 'unknown invnum' };
854     $agentnum = $cust_bill->cust_main->agentnum;
855   }
856
857   my $templatename = $p->{'template'} || $p->{'templatename'};
858
859   #false laziness-ish w/view/cust_bill-logo.cgi
860
861   my $conf = new FS::Conf;
862   if ( $templatename =~ /^([^\.\/]*)$/ && $conf->exists("logo_$1.png") ) {
863     $templatename = "_$1";
864   } else {
865     $templatename = '';
866   }
867
868   my $filename = "logo$templatename.png";
869
870   return { 'error'        => '',
871            'logo'         => $conf->config_binary($filename, $agentnum),
872            'content_type' => 'image/png', #should allow gif, jpg too
873          };
874 }
875
876
877 sub list_invoices {
878   my $p = shift;
879   my $session = _cache->get($p->{'session_id'})
880     or return { 'error' => "Can't resume session" }; #better error message
881
882   my $custnum = $session->{'custnum'};
883
884   my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
885     or return { 'error' => "unknown custnum $custnum" };
886
887   my @cust_bill = $cust_main->cust_bill;
888
889   return  { 'error'       => '',
890             'invoices'    =>  [ map { { 'invnum' => $_->invnum,
891                                         '_date'  => $_->_date,
892                                         'date'   => time2str("%b %o, %Y", $_->_date),
893                                       }
894                                     } @cust_bill
895                               ]
896           };
897 }
898
899 sub cancel {
900   my $p = shift;
901   my $session = _cache->get($p->{'session_id'})
902     or return { 'error' => "Can't resume session" }; #better error message
903
904   my $custnum = $session->{'custnum'};
905
906   my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
907     or return { 'error' => "unknown custnum $custnum" };
908
909   my @errors = $cust_main->cancel( 'quiet'=>1 );
910
911   my $error = scalar(@errors) ? join(' / ', @errors) : '';
912
913   return { 'error' => $error };
914
915 }
916
917 sub list_pkgs {
918   my $p = shift;
919
920   my($context, $session, $custnum) = _custoragent_session_custnum($p);
921   return { 'error' => $session } if $context eq 'error';
922
923   my $search = { 'custnum' => $custnum };
924   $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
925   my $cust_main = qsearchs('cust_main', $search )
926     or return { 'error' => "unknown custnum $custnum" };
927
928   my $conf = new FS::Conf;
929   
930 # the duplication below is necessary:
931 # 1. to maintain the current buggy behaviour wrt the cust_pkg and part_pkg
932 # hashes overwriting each other (setup and no_auto fields). Fixing that is a
933 # non-backwards-compatible change breaking the software of anyone using the API
934 # instead of the stock selfservice
935 # 2. to return cancelled packages as well - for wholesale and non-wholesale
936   if( $conf->exists('selfservice_server-view-wholesale') ) {
937     return { 'svcnum'   => $session->{'svcnum'},
938             'custnum'  => $custnum,
939             'cust_pkg' => [ map {
940                           { $_->hash,
941                             part_pkg => [ map $_->hashref, $_->part_pkg ],
942                             part_svc =>
943                               [ map $_->hashref, $_->available_part_svc ],
944                             cust_svc => 
945                               [ map { my $ref = { $_->hash,
946                                                   label => [ $_->label ],
947                                                 };
948                                       $ref->{_password} = $_->svc_x->_password
949                                         if $context eq 'agent'
950                                         && $conf->exists('agent-showpasswords')
951                                         && $_->part_svc->svcdb eq 'svc_acct';
952                                       $ref;
953                                     } $_->cust_svc
954                               ],
955                           };
956                         } $cust_main->cust_pkg
957                   ],
958     'small_custview' =>
959       small_custview( $cust_main, $conf->config('countrydefault') ),
960     'wholesale_view' => 1,
961     'login_svcpart' => [ $conf->config('selfservice_server-login_svcpart') ],
962     'date_format' => $conf->config('date_format') || '%m/%d/%Y',
963       };
964   }
965
966   { 'svcnum'   => $session->{'svcnum'},
967     'custnum'  => $custnum,
968     'cust_pkg' => [ map {
969                           { $_->hash,
970                             $_->part_pkg->hash,
971                             part_svc =>
972                               [ map $_->hashref, $_->available_part_svc ],
973                             cust_svc => 
974                               [ map { my $ref = { $_->hash,
975                                                   label => [ $_->label ],
976                                                 };
977                                       $ref->{_password} = $_->svc_x->_password
978                                         if $context eq 'agent'
979                                         && $conf->exists('agent-showpasswords')
980                                         && $_->part_svc->svcdb eq 'svc_acct';
981                                       $ref;
982                                     } $_->cust_svc
983                               ],
984                           };
985                         } $cust_main->ncancelled_pkgs
986                   ],
987     'small_custview' =>
988       small_custview( $cust_main, $conf->config('countrydefault') ),
989   };
990
991 }
992
993 sub list_svcs {
994   my $p = shift;
995
996   my($context, $session, $custnum) = _custoragent_session_custnum($p);
997   return { 'error' => $session } if $context eq 'error';
998
999   my $search = { 'custnum' => $custnum };
1000   $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
1001   my $cust_main = qsearchs('cust_main', $search )
1002     or return { 'error' => "unknown custnum $custnum" };
1003
1004   my @cust_svc = ();
1005   #foreach my $cust_pkg ( $cust_main->ncancelled_pkgs ) {
1006   foreach my $cust_pkg ( $p->{'ncancelled'} 
1007                          ? $cust_main->ncancelled_pkgs
1008                          : $cust_main->unsuspended_pkgs ) {
1009     next if $session->{'pkgnum'} && $cust_pkg->pkgnum != $session->{'pkgnum'};
1010     push @cust_svc, @{[ $cust_pkg->cust_svc ]}; #@{[ ]} to force array context
1011   }
1012   if ( $p->{'svcdb'} ) {
1013     my $svcdb = ref($p->{'svcdb'}) eq 'HASH'
1014                   ? $p->{'svcdb'}
1015                   : ref($p->{'svcdb'}) eq 'ARRAY'
1016                     ? { map { $_=>1 } @{ $p->{'svcdb'} } }
1017                     : { $p->{'svcdb'} => 1 };
1018     @cust_svc = grep $svcdb->{ $_->part_svc->svcdb }, @cust_svc
1019   }
1020
1021   #@svc_x = sort { $a->domain cmp $b->domain || $a->username cmp $b->username }
1022   #              @svc_x;
1023
1024   { 
1025     'svcnum'   => $session->{'svcnum'},
1026     'custnum'  => $custnum,
1027     'svcs'     => [
1028       map { 
1029             my $svc_x = $_->svc_x;
1030             my($label, $value) = $_->label;
1031             my $svcdb = $_->part_svc->svcdb;
1032             my $part_pkg = $_->cust_pkg->part_pkg;
1033
1034             my %hash = (
1035               'svcnum' => $_->svcnum,
1036               'svcdb'  => $svcdb,
1037               'label'  => $label,
1038               'value'  => $value,
1039             );
1040
1041             if ( $svcdb eq 'svc_acct' ) {
1042               %hash = (
1043                 %hash,
1044                 'username'   => $svc_x->username,
1045                 'email'      => $svc_x->email,
1046                 'seconds'    => $svc_x->seconds,
1047                 'upbytes'    => display_bytecount($svc_x->upbytes),
1048                 'downbytes'  => display_bytecount($svc_x->downbytes),
1049                 'totalbytes' => display_bytecount($svc_x->totalbytes),
1050
1051                 'recharge_amount'  => $part_pkg->option('recharge_amount',1),
1052                 'recharge_seconds' => $part_pkg->option('recharge_seconds',1),
1053                 'recharge_upbytes'    =>
1054                   display_bytecount($part_pkg->option('recharge_upbytes',1)),
1055                 'recharge_downbytes'  =>
1056                   display_bytecount($part_pkg->option('recharge_downbytes',1)),
1057                 'recharge_totalbytes' =>
1058                   display_bytecount($part_pkg->option('recharge_totalbytes',1)),
1059                 # more...
1060               );
1061
1062             } elsif ( $svcdb eq 'svc_phone' ) {
1063               %hash = (
1064                 %hash,
1065               );
1066             }
1067
1068             \%hash;
1069           }
1070           @cust_svc
1071     ],
1072   };
1073
1074 }
1075
1076 sub _list_svc_usage {
1077   my($svc_acct, $begin, $end) = @_;
1078   my @usage = ();
1079   foreach my $part_export ( 
1080     map { qsearch ( 'part_export', { 'exporttype' => $_ } ) }
1081     qw( sqlradius sqlradius_withdomain )
1082   ) {
1083     push @usage, @ { $part_export->usage_sessions($begin, $end, $svc_acct) };
1084   }
1085   (@usage);
1086 }
1087
1088 sub list_svc_usage {
1089   _usage_details(\&_list_svc_usage, @_);
1090 }
1091
1092 sub _list_support_usage {
1093   my($svc_acct, $begin, $end) = @_;
1094   my @usage = ();
1095   foreach ( grep { $begin <= $_->_date && $_->_date <= $end }
1096             qsearch('acct_rt_transaction', { 'svcnum' => $svc_acct->svcnum })
1097           ) {
1098     push @usage, { 'seconds'  => $_->seconds,
1099                    'support'  => $_->support,
1100                    '_date'    => $_->_date,
1101                    'id'       => $_->transaction_id,
1102                    'creator'  => $_->creator,
1103                    'subject'  => $_->subject,
1104                    'status'   => $_->status,
1105                    'ticketid' => $_->ticketid,
1106                  };
1107   }
1108   (@usage);
1109 }
1110
1111 sub list_support_usage {
1112   _usage_details(\&_list_support_usage, @_);
1113 }
1114
1115 sub _list_cdr_usage {
1116   my($svc_phone, $begin, $end) = @_;
1117   map [ $_->downstream_csv('format' => 'default') ], #XXX config for format
1118       $svc_phone->get_cdrs( 'begin'=>$begin, 'end'=>$end, );
1119 }
1120
1121 sub list_cdr_usage {
1122   my $p = shift;
1123   _usage_details( \&_list_cdr_usage, $p,
1124                   'svcdb' => 'svc_phone',
1125                 );
1126 }
1127
1128 sub _usage_details {
1129   my($callback, $p, %opt) = @_;
1130
1131   my($context, $session, $custnum) = _custoragent_session_custnum($p);
1132   return { 'error' => $session } if $context eq 'error';
1133
1134   my $search = { 'svcnum' => $p->{'svcnum'} };
1135   $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
1136
1137   my $svcdb = $opt{'svcdb'} || 'svc_acct';
1138
1139   my $svc_x = qsearchs( $svcdb, $search );
1140   return { 'error' => 'No service selected in list_svc_usage' } 
1141     unless $svc_x;
1142
1143   my $header = $svcdb eq 'svc_phone'
1144                  ? [ split(',', FS::cdr::invoice_header('default') ) ]  #XXX
1145                  : [];
1146
1147   my $cust_pkg = $svc_x->cust_svc->cust_pkg;
1148   my $freq     = $cust_pkg->part_pkg->freq;
1149   my $start    = $cust_pkg->setup;
1150   #my $end      = $cust_pkg->bill; # or time?
1151   my $end      = time;
1152
1153   unless ( $p->{beginning} ) {
1154     $p->{beginning} = $cust_pkg->last_bill;
1155     $p->{ending}    = $end;
1156   }
1157
1158   my (@usage) = &$callback($svc_x, $p->{beginning}, $p->{ending});
1159
1160   #kinda false laziness with FS::cust_main::bill, but perhaps
1161   #we should really change this bit to DateTime and DateTime::Duration
1162   #
1163   #change this bit to use Date::Manip? CAREFUL with timezones (see
1164   # mailing list archive)
1165   my ($nsec,$nmin,$nhour,$nmday,$nmon,$nyear) =
1166     (localtime($p->{ending}) )[0,1,2,3,4,5];
1167   my ($psec,$pmin,$phour,$pmday,$pmon,$pyear) =
1168     (localtime($p->{beginning}) )[0,1,2,3,4,5];
1169
1170   if ( $freq =~ /^\d+$/ ) {
1171     $nmon += $freq;
1172     until ( $nmon < 12 ) { $nmon -= 12; $nyear++; }
1173     $pmon -= $freq;
1174     until ( $pmon >= 0 ) { $pmon += 12; $pyear--; }
1175   } elsif ( $freq =~ /^(\d+)w$/ ) {
1176     my $weeks = $1;
1177     $nmday += $weeks * 7;
1178     $pmday -= $weeks * 7;
1179   } elsif ( $freq =~ /^(\d+)d$/ ) {
1180     my $days = $1;
1181     $nmday += $days;
1182     $pmday -= $days;
1183   } elsif ( $freq =~ /^(\d+)h$/ ) {
1184     my $hours = $1;
1185     $nhour += $hours;
1186     $phour -= $hours;
1187   } else {
1188     return { 'error' => "unparsable frequency: ". $freq };
1189   }
1190   
1191   my $previous  = timelocal_nocheck($psec,$pmin,$phour,$pmday,$pmon,$pyear);
1192   my $next      = timelocal_nocheck($nsec,$nmin,$nhour,$nmday,$nmon,$nyear);
1193
1194   { 
1195     'error'     => '',
1196     'svcnum'    => $p->{svcnum},
1197     'beginning' => $p->{beginning},
1198     'ending'    => $p->{ending},
1199     'previous'  => ($previous > $start) ? $previous : $start,
1200     'next'      => ($next < $end) ? $next : $end,
1201     'header'    => $header,
1202     'usage'     => \@usage,
1203   };
1204 }
1205
1206 sub order_pkg {
1207   my $p = shift;
1208
1209   my($context, $session, $custnum) = _custoragent_session_custnum($p);
1210   return { 'error' => $session } if $context eq 'error';
1211
1212   my $search = { 'custnum' => $custnum };
1213   $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
1214   my $cust_main = qsearchs('cust_main', $search )
1215     or return { 'error' => "unknown custnum $custnum" };
1216
1217   my $status = $cust_main->status;
1218   #false laziness w/ClientAPI/Signup.pm
1219
1220   my $cust_pkg = new FS::cust_pkg ( {
1221     'custnum' => $custnum,
1222     'pkgpart' => $p->{'pkgpart'},
1223   } );
1224   my $error = $cust_pkg->check;
1225   return { 'error' => $error } if $error;
1226
1227   my @svc = ();
1228   unless ( $p->{'svcpart'} eq 'none' ) {
1229
1230     my $svcdb;
1231     my $svcpart = '';
1232     if ( $p->{'svcpart'} =~ /^(\d+)$/ ) {
1233       $svcpart = $1;
1234       my $part_svc = qsearchs('part_svc', { 'svcpart' => $svcpart } );
1235       return { 'error' => "Unknown svcpart $svcpart" } unless $part_svc;
1236       $svcdb = $part_svc->svcdb;
1237     } else {
1238       $svcdb = 'svc_acct';
1239     }
1240     $svcpart ||= $cust_pkg->part_pkg->svcpart($svcdb);
1241
1242     my %fields = (
1243       'svc_acct'     => [ qw( username domsvc _password sec_phrase popnum ) ],
1244       'svc_domain'   => [ qw( domain ) ],
1245       'svc_phone'    => [ qw( phonenum pin sip_password phone_name ) ],
1246       'svc_external' => [ qw( id title ) ],
1247       'svc_pbx'      => [ qw( id name ) ],
1248     );
1249   
1250     my $svc_x = "FS::$svcdb"->new( {
1251       'svcpart'   => $svcpart,
1252       map { $_ => $p->{$_} } @{$fields{$svcdb}}
1253     } );
1254     
1255     if ( $svcdb eq 'svc_acct' ) {
1256       my @acct_snarf;
1257       my $snarfnum = 1;
1258       while ( length($p->{"snarf_machine$snarfnum"}) ) {
1259         my $acct_snarf = new FS::acct_snarf ( {
1260           'machine'   => $p->{"snarf_machine$snarfnum"},
1261           'protocol'  => $p->{"snarf_protocol$snarfnum"},
1262           'username'  => $p->{"snarf_username$snarfnum"},
1263           '_password' => $p->{"snarf_password$snarfnum"},
1264         } );
1265         $snarfnum++;
1266         push @acct_snarf, $acct_snarf;
1267       }
1268       $svc_x->child_objects( \@acct_snarf );
1269     }
1270     
1271     my $y = $svc_x->setdefault; # arguably should be in new method
1272     return { 'error' => $y } if $y && !ref($y);
1273   
1274     $error = $svc_x->check;
1275     return { 'error' => $error } if $error;
1276
1277     push @svc, $svc_x;
1278
1279   }
1280
1281   use Tie::RefHash;
1282   tie my %hash, 'Tie::RefHash';
1283   %hash = ( $cust_pkg => \@svc );
1284   #msgcat
1285   $error = $cust_main->order_pkgs( \%hash, '', 'noexport' => 1 );
1286   return { 'error' => $error } if $error;
1287
1288   my $conf = new FS::Conf;
1289   if ( $conf->exists('signup_server-realtime') ) {
1290
1291     my $bill_error = _do_bop_realtime( $cust_main, $status );
1292
1293     if ($bill_error) {
1294       $cust_pkg->cancel('quiet'=>1);
1295       return $bill_error;
1296     } else {
1297       $cust_pkg->reexport;
1298     }
1299
1300   } else {
1301     $cust_pkg->reexport;
1302   }
1303
1304   my $svcnum = $svc[0] ? $svc[0]->svcnum : '';
1305
1306   return { error=>'', pkgnum=>$cust_pkg->pkgnum, svcnum=>$svcnum };
1307
1308 }
1309
1310 sub change_pkg {
1311   my $p = shift;
1312
1313   my($context, $session, $custnum) = _custoragent_session_custnum($p);
1314   return { 'error' => $session } if $context eq 'error';
1315
1316   my $search = { 'custnum' => $custnum };
1317   $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
1318   my $cust_main = qsearchs('cust_main', $search )
1319     or return { 'error' => "unknown custnum $custnum" };
1320
1321   my $status = $cust_main->status;
1322   my $cust_pkg = qsearchs('cust_pkg', { 'pkgnum' => $p->{pkgnum} } )
1323     or return { 'error' => "unknown package $p->{pkgnum}" };
1324
1325   my @newpkg;
1326   my $error = FS::cust_pkg::order( $custnum,
1327                                    [$p->{pkgpart}],
1328                                    [$p->{pkgnum}],
1329                                    \@newpkg,
1330                                  );
1331
1332   my $conf = new FS::Conf;
1333   if ( $conf->exists('signup_server-realtime') ) {
1334
1335     my $bill_error = _do_bop_realtime( $cust_main, $status );
1336
1337     if ($bill_error) {
1338       $newpkg[0]->suspend;
1339       return $bill_error;
1340     } else {
1341       $newpkg[0]->reexport;
1342     }
1343
1344   } else {  
1345     $newpkg[0]->reexport;
1346   }
1347
1348   return { error => '', pkgnum => $cust_pkg->pkgnum };
1349
1350 }
1351
1352 sub order_recharge {
1353   my $p = shift;
1354
1355   my($context, $session, $custnum) = _custoragent_session_custnum($p);
1356   return { 'error' => $session } if $context eq 'error';
1357
1358   my $search = { 'custnum' => $custnum };
1359   $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
1360   my $cust_main = qsearchs('cust_main', $search )
1361     or return { 'error' => "unknown custnum $custnum" };
1362
1363   my $status = $cust_main->status;
1364   my $cust_svc = qsearchs( 'cust_svc', { 'svcnum' => $p->{'svcnum'} } )
1365     or return { 'error' => "unknown service " . $p->{'svcnum'} };
1366
1367   my $svc_x = $cust_svc->svc_x;
1368   my $part_pkg = $cust_svc->cust_pkg->part_pkg;
1369
1370   my %vhash =
1371     map { $_ =~ /^recharge_(.*)$/; $1, $part_pkg->option($_, 1) } 
1372     qw ( recharge_seconds recharge_upbytes recharge_downbytes
1373          recharge_totalbytes );
1374   my $amount = $part_pkg->option('recharge_amount', 1); 
1375   
1376   my ($l, $v, $d) = $cust_svc->label;  # blah
1377   my $pkg = "Recharge $v"; 
1378
1379   my $bill_error = $cust_main->charge($amount, $pkg,
1380      "time: $vhash{seconds}, up: $vhash{upbytes}," . 
1381      "down: $vhash{downbytes}, total: $vhash{totalbytes}",
1382      $part_pkg->taxclass); #meh
1383
1384   my $conf = new FS::Conf;
1385   if ( $conf->exists('signup_server-realtime') && !$bill_error ) {
1386
1387     $bill_error = _do_bop_realtime( $cust_main, $status );
1388
1389     if ($bill_error) {
1390       return $bill_error;
1391     } else {
1392       my $error = $svc_x->recharge (\%vhash);
1393       return { 'error' => $error } if $error;
1394     }
1395
1396   } else {  
1397     my $error = $bill_error;
1398     $error ||= $svc_x->recharge (\%vhash);
1399     return { 'error' => $error } if $error;
1400   }
1401
1402   return { error => '', svc => $cust_svc->part_svc->svc };
1403
1404 }
1405
1406 sub _do_bop_realtime {
1407   my ($cust_main, $status) = (shift, shift);
1408
1409     my $old_balance = $cust_main->balance;
1410
1411     my $bill_error =    $cust_main->bill
1412                      || $cust_main->apply_payments_and_credits
1413                      || $cust_main->realtime_collect;
1414
1415     if (    $cust_main->balance > $old_balance
1416          && $cust_main->balance > 0
1417          && ( $cust_main->payby !~ /^(BILL|DCRD|DCHK)$/ ?
1418               1 : $status eq 'suspended' ) ) {
1419       #this makes sense.  credit is "un-doing" the invoice
1420       my $conf = new FS::Conf;
1421       $cust_main->credit( sprintf("%.2f", $cust_main->balance - $old_balance ),
1422                           'self-service decline',
1423                           'reason_type' => $conf->config('signup_credit_type'),
1424                         );
1425       $cust_main->apply_credits( 'order' => 'newest' );
1426
1427       return { 'error' => '_decline', 'bill_error' => $bill_error };
1428     }
1429
1430     '';
1431 }
1432
1433 sub renew_info {
1434   my $p = shift;
1435
1436   my($context, $session, $custnum) = _custoragent_session_custnum($p);
1437   return { 'error' => $session } if $context eq 'error';
1438
1439   my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1440     or return { 'error' => "unknown custnum $custnum" };
1441
1442   my @cust_pkg = sort { $a->bill <=> $b->bill }
1443                  grep { $_->part_pkg->freq ne '0' }
1444                  $cust_main->ncancelled_pkgs;
1445
1446   #return { 'error' => 'No active packages to renew.' } unless @cust_pkg;
1447
1448   my $total = $cust_main->balance;
1449
1450   my @array = map {
1451                     my $bill = $_->bill;
1452                     $total += $_->part_pkg->base_recur($_, \$bill);
1453                     my $renew_date = $_->part_pkg->add_freq($_->bill);
1454                     {
1455                       'pkgnum'             => $_->pkgnum,
1456                       'amount'             => sprintf('%.2f', $total),
1457                       'bill_date'          => $_->bill,
1458                       'bill_date_pretty'   => time2str('%x', $_->bill),
1459                       'renew_date'         => $renew_date,
1460                       'renew_date_pretty'  => time2str('%x', $renew_date),
1461                       'expire_date'        => $_->expire,
1462                       'expire_date_pretty' => time2str('%x', $_->expire),
1463                     };
1464                   }
1465                   @cust_pkg;
1466
1467   return { 'dates' => \@array };
1468
1469 }
1470
1471 sub payment_info_renew_info {
1472   my $p = shift;
1473   my $renew_info   = renew_info($p);
1474   my $payment_info = payment_info($p);
1475   return { %$renew_info,
1476            %$payment_info,
1477          };
1478 }
1479
1480 sub order_renew {
1481   my $p = shift;
1482
1483   my($context, $session, $custnum) = _custoragent_session_custnum($p);
1484   return { 'error' => $session } if $context eq 'error';
1485
1486   my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1487     or return { 'error' => "unknown custnum $custnum" };
1488
1489   my $date = $p->{'date'};
1490
1491   my $now = time;
1492
1493   #freeside-daily -n -d $date fs_daily $custnum
1494   $cust_main->bill_and_collect( 'time'         => $date,
1495                                 'invoice_time' => $now,
1496                                 'actual_time'  => $now,
1497                                 'check_freq'   => '1d',
1498                               );
1499
1500   return { 'error' => '' };
1501
1502 }
1503
1504 sub suspend_pkg {
1505   my $p = shift;
1506   my $session = _cache->get($p->{'session_id'})
1507     or return { 'error' => "Can't resume session" }; #better error message
1508
1509   my $custnum = $session->{'custnum'};
1510
1511   my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1512     or return { 'error' => "unknown custnum $custnum" };
1513
1514   my $conf = new FS::Conf;
1515   my $reasonnum = 
1516     $conf->config('selfservice-self_suspend_reason', $cust_main->agentnum)
1517       or return { 'error' => 'Permission denied' };
1518
1519   my $pkgnum = $p->{'pkgnum'};
1520
1521   my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
1522                                         'pkgnum'  => $pkgnum,   } )
1523     or return { 'error' => "unknown pkgnum $pkgnum" };
1524
1525   my $error = $cust_pkg->suspend(reason => $reasonnum);
1526   return { 'error' => $error };
1527
1528 }
1529
1530 sub cancel_pkg {
1531   my $p = shift;
1532   my $session = _cache->get($p->{'session_id'})
1533     or return { 'error' => "Can't resume session" }; #better error message
1534
1535   my $custnum = $session->{'custnum'};
1536
1537   my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1538     or return { 'error' => "unknown custnum $custnum" };
1539
1540   my $pkgnum = $p->{'pkgnum'};
1541
1542   my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
1543                                         'pkgnum'  => $pkgnum,   } )
1544     or return { 'error' => "unknown pkgnum $pkgnum" };
1545
1546   my $error = $cust_pkg->cancel('quiet' => 1);
1547   return { 'error' => $error };
1548
1549 }
1550
1551 sub provision_phone {
1552  my $p = shift;
1553  my @bulkdid = @{$p->{'bulkdid'}};
1554  unless (scalar(@bulkdid)) {
1555     return _provision( 'FS::svc_phone',
1556                   [qw(phonenum countrycode)],
1557                   [qw(phonenum countrycode)],
1558                   $p,
1559                   @_
1560                 );
1561  }
1562 #XXX: finish bulk orders
1563 }
1564
1565 sub provision_acct {
1566   my $p = shift;
1567   warn "provision_acct called\n"
1568     if $DEBUG;
1569
1570   return { 'error' => gettext('passwords_dont_match') }
1571     if $p->{'_password'} ne $p->{'_password2'};
1572   return { 'error' => gettext('empty_password') }
1573     unless length($p->{'_password'});
1574  
1575   if ($p->{'domsvc'}) {
1576     my %domains = domain_select_hash FS::svc_acct(map { $_ => $p->{$_} }
1577                                                   qw ( svcpart pkgnum ) );
1578     return { 'error' => gettext('invalid_domain') }
1579       unless ($domains{$p->{'domsvc'}});
1580   }
1581
1582   warn "provision_acct calling _provision\n"
1583     if $DEBUG;
1584   _provision( 'FS::svc_acct',
1585               [qw(username _password domsvc)],
1586               [qw(username _password domsvc)],
1587               $p,
1588               @_
1589             );
1590 }
1591
1592 sub provision_external {
1593   my $p = shift;
1594   #_provision( 'FS::svc_external', [qw(id title)], [qw(id title)], $p, @_ );
1595   _provision( 'FS::svc_external',
1596               [],
1597               [qw(id title)],
1598               $p,
1599               @_
1600             );
1601 }
1602
1603 sub _provision {
1604   my( $class, $fields, $return_fields, $p ) = splice(@_, 0, 4);
1605   warn "_provision called for $class\n"
1606     if $DEBUG;
1607
1608   my($context, $session, $custnum) = _custoragent_session_custnum($p);
1609   return { 'error' => $session } if $context eq 'error';
1610
1611   my $search = { 'custnum' => $custnum };
1612   $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
1613   my $cust_main = qsearchs('cust_main', $search )
1614     or return { 'error' => "unknown custnum $custnum" };
1615
1616   my $pkgnum = $p->{'pkgnum'};
1617
1618   warn "searching for custnum $custnum pkgnum $pkgnum\n"
1619     if $DEBUG;
1620   my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
1621                                         'pkgnum'  => $pkgnum,
1622                                                                } )
1623     or return { 'error' => "unknown pkgnum $pkgnum" };
1624
1625   warn "searching for svcpart ". $p->{'svcpart'}. "\n"
1626     if $DEBUG;
1627   my $part_svc = qsearchs('part_svc', { 'svcpart' => $p->{'svcpart'} } )
1628     or return { 'error' => "unknown svcpart $p->{'svcpart'}" };
1629
1630   warn "creating $class record\n"
1631     if $DEBUG;
1632   my $svc_x = $class->new( {
1633     'pkgnum'  => $p->{'pkgnum'},
1634     'svcpart' => $p->{'svcpart'},
1635     map { $_ => $p->{$_} } @$fields
1636   } );
1637   warn "inserting $class record\n"
1638     if $DEBUG;
1639   my $error = $svc_x->insert;
1640
1641   unless ( $error ) {
1642     warn "finding inserted record for svcnum ". $svc_x->svcnum. "\n"
1643       if $DEBUG;
1644     $svc_x = qsearchs($svc_x->table, { 'svcnum' => $svc_x->svcnum })
1645   }
1646
1647   my $return = { 'svc'   => $part_svc->svc,
1648                  'error' => $error,
1649                  map { $_ => $svc_x->get($_) } @$return_fields
1650                };
1651   warn "_provision returning ". Dumper($return). "\n"
1652     if $DEBUG;
1653   return $return;
1654
1655 }
1656
1657 sub part_svc_info {
1658   my $p = shift;
1659
1660   my($context, $session, $custnum) = _custoragent_session_custnum($p);
1661   return { 'error' => $session } if $context eq 'error';
1662
1663   my $search = { 'custnum' => $custnum };
1664   $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
1665   my $cust_main = qsearchs('cust_main', $search )
1666     or return { 'error' => "unknown custnum $custnum" };
1667
1668   my $pkgnum = $p->{'pkgnum'};
1669
1670   my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
1671                                         'pkgnum'  => $pkgnum,
1672                                                                } )
1673     or return { 'error' => "unknown pkgnum $pkgnum" };
1674
1675   my $svcpart = $p->{'svcpart'};
1676
1677   my $pkg_svc = qsearchs('pkg_svc', { 'pkgpart' => $cust_pkg->pkgpart,
1678                                       'svcpart' => $svcpart,           } )
1679     or return { 'error' => "unknown svcpart $svcpart for pkgnum $pkgnum" };
1680   my $part_svc = $pkg_svc->part_svc;
1681
1682   my $conf = new FS::Conf;
1683
1684   return {
1685     'svc'     => $part_svc->svc,
1686     'svcdb'   => $part_svc->svcdb,
1687     'pkgnum'  => $pkgnum,
1688     'svcpart' => $svcpart,
1689     'custnum' => $custnum,
1690
1691     'security_phrase' => 0, #XXX !
1692     'svc_acct_pop'    => [], #XXX !
1693     'popnum'          => '',
1694     'init_popstate'   => '',
1695     'popac'           => '',
1696     'acstate'         => '',
1697
1698     'small_custview' =>
1699       small_custview( $cust_main, $conf->config('countrydefault') ),
1700
1701   };
1702
1703 }
1704
1705 sub unprovision_svc {
1706   my $p = shift;
1707
1708   my($context, $session, $custnum) = _custoragent_session_custnum($p);
1709   return { 'error' => $session } if $context eq 'error';
1710
1711   my $search = { 'custnum' => $custnum };
1712   $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
1713   my $cust_main = qsearchs('cust_main', $search )
1714     or return { 'error' => "unknown custnum $custnum" };
1715
1716   my $svcnum = $p->{'svcnum'};
1717
1718   my $cust_svc = qsearchs('cust_svc', { 'svcnum'  => $svcnum, } )
1719     or return { 'error' => "unknown svcnum $svcnum" };
1720
1721   return { 'error' => "Service $svcnum does not belong to customer $custnum" }
1722     unless $cust_svc->cust_pkg->custnum == $custnum;
1723
1724   my $conf = new FS::Conf;
1725
1726   return { 'svc'   => $cust_svc->part_svc->svc,
1727            'error' => $cust_svc->cancel,
1728            'small_custview' =>
1729              small_custview( $cust_main, $conf->config('countrydefault') ),
1730          };
1731
1732 }
1733
1734 sub myaccount_passwd {
1735   my $p = shift;
1736   my($context, $session, $custnum) = _custoragent_session_custnum($p);
1737   return { 'error' => $session } if $context eq 'error';
1738
1739   return { 'error' => "New passwords don't match." }
1740     if $p->{'new_password'} ne $p->{'new_password2'};
1741
1742   return { 'error' => 'Enter new password' }
1743     unless length($p->{'new_password'});
1744
1745   #my $search = { 'custnum' => $custnum };
1746   #$search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
1747   $custnum =~ /^(\d+)$/ or die "illegal custnum";
1748   my $search = " AND custnum = $1";
1749   $search .= " AND agentnum = ". $session->{'agentnum'} if $context eq 'agent';
1750
1751   my $svc_acct = qsearchs( {
1752     'table'     => 'svc_acct',
1753     'addl_from' => 'LEFT JOIN cust_svc  USING ( svcnum  ) '.
1754                    'LEFT JOIN cust_pkg  USING ( pkgnum  ) '.
1755                    'LEFT JOIN cust_main USING ( custnum ) ',
1756     'hashref'   => { 'svcnum' => $p->{'svcnum'}, },
1757     'extra_sql' => $search, #important
1758   } )
1759     or return { 'error' => "Service not found" };
1760
1761   $svc_acct->_password($p->{'new_password'});
1762   my $error = $svc_acct->replace();
1763
1764   my($label, $value) = $svc_acct->cust_svc->label;
1765
1766   return { 'error' => $error,
1767            'label' => $label,
1768            'value' => $value,
1769          };
1770
1771 }
1772
1773 sub create_ticket {
1774   my $p = shift;
1775   my($context, $session, $custnum) = _custoragent_session_custnum($p);
1776   return { 'error' => $session } if $context eq 'error';
1777
1778   warn "$me create_ticket: initializing ticket system\n" if $DEBUG;
1779   FS::TicketSystem->init();
1780
1781   my $conf = new FS::Conf;
1782   my $queue = $p->{'queue'}
1783               || $conf->config('ticket_system-selfservice_queueid')
1784               || $conf->config('ticket_system-default_queueid');
1785
1786   warn "$me create_ticket: creating ticket\n" if $DEBUG;
1787   my $err_or_ticket = FS::TicketSystem->create_ticket(
1788     '', #create RT session based on FS CurrentUser (fs_selfservice)
1789     'queue'   => $queue,
1790     'custnum' => $custnum,
1791     'svcnum'  => $session->{'svcnum'},
1792     map { $_ => $p->{$_} } qw( requestor cc subject message mime_type )
1793   );
1794
1795   if ( ref($err_or_ticket) ) {
1796     warn "$me create_ticket: sucessful: ". $err_or_ticket->id. "\n"
1797       if $DEBUG;
1798     return { 'error'     => '',
1799              'ticket_id' => $err_or_ticket->id,
1800            };
1801   } else {
1802     warn "$me create_ticket: unsucessful: $err_or_ticket\n"
1803       if $DEBUG;
1804     return { 'error' => $err_or_ticket };
1805   }
1806
1807
1808 }
1809
1810 sub did_report {
1811   my $p = shift;
1812   my($context, $session, $custnum) = _custoragent_session_custnum($p);
1813   return { 'error' => $session } if $context eq 'error';
1814  
1815   return { error => 'requested format not implemented' } 
1816     unless ($p->{'format'} eq 'csv' || $p->{'format'} eq 'xls');
1817
1818   my $conf = new FS::Conf;
1819   my $age_threshold = 0;
1820   $age_threshold = time() - $conf->config('selfservice-recent-did-age')
1821     if ($p->{'recentonly'} && $conf->exists('selfservice-recent-did-age'));
1822
1823   my $search = { 'custnum' => $custnum };
1824   $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
1825   my $cust_main = qsearchs('cust_main', $search )
1826     or return { 'error' => "unknown custnum $custnum" };
1827
1828 # does it make more sense to just run one sql query for this instead of all the
1829 # insanity below? would increase performance greately for large data sets?
1830   my @svc_phone = ();
1831   foreach my $cust_pkg ( $cust_main->ncancelled_pkgs ) {
1832         my @part_svc = $cust_pkg->part_svc;
1833         foreach my $part_svc ( @part_svc ) {
1834             if($part_svc->svcdb eq 'svc_phone'){
1835                 my @cust_pkg_svc = @{$part_svc->cust_pkg_svc};
1836                 foreach my $cust_pkg_svc ( @cust_pkg_svc ) {
1837                     push @svc_phone, $cust_pkg_svc->svc_x
1838                         if $cust_pkg_svc->date_inserted >= $age_threshold;
1839                 }
1840             }
1841         }
1842   }
1843
1844   my $csv;
1845   my $xls;
1846   my($xls_r,$xls_c) = (0,0);
1847   my $xls_workbook;
1848   my $content = '';
1849   my @fields = qw( countrycode phonenum pin sip_password phone_name );
1850   if($p->{'format'} eq 'csv') {
1851     $csv = new Text::CSV_XS { 'always_quote' => 1,
1852                                  'eol'          => "\n",
1853                                 };
1854     return { 'error' => 'Unable to create CSV' } unless $csv->combine(@fields);
1855     $content .= $csv->string;
1856   }
1857   elsif($p->{'format'} eq 'xls') {
1858     my $XLS1 = new IO::Scalar \$content;
1859     $xls_workbook = Spreadsheet::WriteExcel->new($XLS1) 
1860         or return { 'error' => "Error opening .xls file: $!" };
1861     $xls = $xls_workbook->add_worksheet('DIDs');
1862     foreach ( @fields ) {
1863         $xls->write(0,$xls_c++,$_);
1864     }
1865     $xls_r++;
1866   }
1867
1868   foreach my $svc_phone ( @svc_phone ) {
1869     my @cols = map { $svc_phone->$_ } @fields;
1870     if($p->{'format'} eq 'csv') {
1871         return { 'error' => 'Unable to create CSV' } 
1872             unless $csv->combine(@cols);
1873         $content .= $csv->string;
1874     }
1875     elsif($p->{'format'} eq 'xls') {
1876         $xls_c = 0;
1877         foreach ( @cols ) {
1878             $xls->write($xls_r,$xls_c++,$_);
1879         }
1880         $xls_r++;
1881     }
1882   }
1883
1884   $xls_workbook->close() if $p->{'format'} eq 'xls';
1885   
1886   { content => $content, format => $p->{'format'}, };
1887 }
1888
1889 sub get_ticket {
1890   my $p = shift;
1891   my($context, $session, $custnum) = _custoragent_session_custnum($p);
1892   return { 'error' => $session } if $context eq 'error';
1893
1894   warn "$me get_ticket: initializing ticket system\n" if $DEBUG;
1895   FS::TicketSystem->init();
1896
1897   if(length($p->{'reply'})) {
1898 # currently this allows anyone to correspond on any ticket as fs_selfservice
1899 # probably bad...
1900       my @err_or_res = FS::TicketSystem->correspond_ticket(
1901         '', #create RT session based on FS CurrentUser (fs_selfservice)
1902         'ticket_id' => $p->{'ticket_id'},
1903         'content' => $p->{'reply'},
1904       );
1905     
1906     return { 'error' => 'unable to reply to ticket' } 
1907         unless ( $err_or_res[0] != 0 && defined $err_or_res[2] );
1908   }
1909
1910   warn "$me get_ticket: getting ticket\n" if $DEBUG;
1911   my $err_or_ticket = FS::TicketSystem->get_ticket(
1912     '', #create RT session based on FS CurrentUser (fs_selfservice)
1913     'ticket_id' => $p->{'ticket_id'},
1914   );
1915
1916   if ( ref($err_or_ticket) ) {
1917
1918 # since we're bypassing the RT security/permissions model by always using
1919 # fs_selfservice as the RT user (as opposed to a requestor, which we
1920 # can't do since we want all tickets linked to a cust), we check below whether
1921 # the requested ticket was actually linked to this customer
1922     my @custs = @{$err_or_ticket->{'custs'}};
1923     my @txns = @{$err_or_ticket->{'txns'}};
1924
1925     return { 'error' => 'no customer' } unless ( $custnum && scalar(@custs) );
1926
1927     return { 'error' => 'invalid ticket requested' } 
1928         unless grep($_ eq $custnum, @custs);
1929
1930     warn "$me get_ticket: sucessful: \n"
1931       if $DEBUG;
1932     return { 'error'     => '',
1933              'transactions' => \@txns,
1934              'ticket_id' => $p->{'ticket_id'},
1935            };
1936   } else {
1937     warn "$me create_ticket: unsucessful: $err_or_ticket\n"
1938       if $DEBUG;
1939     return { 'error' => $err_or_ticket };
1940   }
1941 }
1942
1943
1944 #--
1945
1946 sub _custoragent_session_custnum {
1947   my $p = shift;
1948
1949   my($context, $session, $custnum);
1950   if ( $p->{'session_id'} ) {
1951
1952     $context = 'customer';
1953     $session = _cache->get($p->{'session_id'})
1954       or return ( 'error' => "Can't resume session" ); #better error message
1955     $custnum = $session->{'custnum'};
1956
1957   } elsif ( $p->{'agent_session_id'} ) {
1958
1959     $context = 'agent';
1960     my $agent_cache = new FS::ClientAPI_SessionCache( {
1961       'namespace' => 'FS::ClientAPI::Agent',
1962     } );
1963     $session = $agent_cache->get($p->{'agent_session_id'})
1964       or return ( 'error' => "Can't resume session" ); #better error message
1965     $custnum = $p->{'custnum'};
1966
1967   } else {
1968     $context = 'error';
1969     return ( 'error' => "Can't resume session" ); #better error message
1970   }
1971
1972   ($context, $session, $custnum);
1973
1974 }
1975
1976 1;
1977