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