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