self-service view usage customization and CDR display fixes, RT11761
[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');
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
538   }
539
540   ##
541   #customer-specific
542   ##
543
544   my %return = %$payment_info;
545
546   my $custnum = $session->{'custnum'};
547
548   my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
549     or return { 'error' => "unknown custnum $custnum" };
550
551   $return{'hide_payment_fields'} = [
552     map { 
553       my $pg = payment_gateway($cust_main, $_);
554       $pg && $pg->gateway_namespace eq 'Business::OnlineThirdPartyPayment';
555     } @{ $return{cust_paybys} }
556   ];
557
558   $return{balance} = $cust_main->balance; #XXX pkg-balances?
559
560   $return{payname} = $cust_main->payname
561                      || ( $cust_main->first. ' '. $cust_main->get('last') );
562
563   $return{$_} = $cust_main->get($_) for qw(address1 address2 city state zip);
564
565   $return{payby} = $cust_main->payby;
566   $return{stateid_state} = $cust_main->stateid_state;
567
568   if ( $cust_main->payby =~ /^(CARD|DCRD)$/ ) {
569     $return{card_type} = cardtype($cust_main->payinfo);
570     $return{payinfo} = $cust_main->paymask;
571
572     @return{'month', 'year'} = $cust_main->paydate_monthyear;
573
574   }
575
576   if ( $cust_main->payby =~ /^(CHEK|DCHK)$/ ) {
577     my ($payinfo1, $payinfo2) = split '@', $cust_main->paymask;
578     $return{payinfo1} = $payinfo1;
579     $return{payinfo2} = $payinfo2;
580     $return{paytype}  = $cust_main->paytype;
581     $return{paystate} = $cust_main->paystate;
582
583   }
584
585   if ( $conf->config('prepayment_discounts-credit_type') ) {
586     #need to eval?
587     $return{discount_terms_hash} = { $cust_main->discount_terms_hash };
588   }
589
590   #doubleclick protection
591   my $_date = time;
592   $return{paybatch} = "webui-MyAccount-$_date-$$-". rand() * 2**32;
593
594   return { 'error' => '',
595            %return,
596          };
597
598 };
599
600 #some false laziness with httemplate/process/payment.cgi - look there for
601 #ACH and CVV support stuff
602 sub process_payment {
603
604   my $p = shift;
605
606   my $session = _cache->get($p->{'session_id'})
607     or return { 'error' => "Can't resume session" }; #better error message
608
609   my %return;
610
611   my $custnum = $session->{'custnum'};
612
613   my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
614     or return { 'error' => "unknown custnum $custnum" };
615
616   $p->{'amount'} =~ /^\s*(\d+(\.\d{2})?)\s*$/
617     or return { 'error' => gettext('illegal_amount') };
618   my $amount = $1;
619   return { error => 'Amount must be greater than 0' } unless $amount > 0;
620
621   $p->{'discount_term'} =~ /^\s*(\d*)\s*$/
622     or return { 'error' => gettext('illegal_discount_term'). ': '. $p->{'discount_term'} };
623   my $discount_term = $1;
624
625   $p->{'payname'} =~ /^([\w \,\.\-\']+)$/
626     or return { 'error' => gettext('illegal_name'). " payname: ". $p->{'payname'} };
627   my $payname = $1;
628
629   $p->{'paybatch'} =~ /^([\w \!\@\#\$\%\&\(\)\-\+\;\:\'\"\,\.\?\/\=]*)$/
630     or return { 'error' => gettext('illegal_text'). " paybatch: ". $p->{'paybatch'} };
631   my $paybatch = $1;
632
633   $p->{'payby'} ||= 'CARD';
634   $p->{'payby'} =~ /^([A-Z]{4})$/
635     or return { 'error' => "illegal_payby " . $p->{'payby'} };
636   my $payby = $1;
637
638   #false laziness w/process/payment.cgi
639   my $payinfo;
640   my $paycvv = '';
641   my $paynum = '';
642   if ( $payby eq 'CHEK' || $payby eq 'DCHK' ) {
643   
644     $p->{'payinfo1'} =~ /^([\dx]+)$/
645       or return { 'error' => "illegal account number ". $p->{'payinfo1'} };
646     my $payinfo1 = $1;
647      $p->{'payinfo2'} =~ /^([\dx]+)$/
648       or return { 'error' => "illegal ABA/routing number ". $p->{'payinfo2'} };
649     my $payinfo2 = $1;
650     $payinfo = $payinfo1. '@'. $payinfo2;
651
652     $payinfo = $cust_main->payinfo
653       if $cust_main->paymask eq $payinfo;
654    
655   } elsif ( $payby eq 'CARD' || $payby eq 'DCRD' ) {
656    
657     $payinfo = $p->{'payinfo'};
658
659     #more intelligent mathing will be needed here if you change
660     #card_masking_method and don't remove existing paymasks
661     $payinfo = $cust_main->payinfo
662       if $cust_main->paymask eq $payinfo;
663
664     $payinfo =~ s/\D//g;
665     $payinfo =~ /^(\d{13,16})$/
666       or return { 'error' => gettext('invalid_card') }; # . ": ". $self->payinfo
667     $payinfo = $1;
668
669     validate($payinfo)
670       or return { 'error' => gettext('invalid_card') }; # . ": ". $self->payinfo
671     return { 'error' => gettext('unknown_card_type') }
672       if $payinfo !~ /^99\d{14}$/ && cardtype($payinfo) eq "Unknown";
673
674     if ( length($p->{'paycvv'}) && $p->{'paycvv'} !~ /^\s*$/ ) {
675       if ( cardtype($payinfo) eq 'American Express card' ) {
676         $p->{'paycvv'} =~ /^\s*(\d{4})\s*$/
677           or return { 'error' => "CVV2 (CID) for American Express cards is four digits." };
678         $paycvv = $1;
679       } else {
680         $p->{'paycvv'} =~ /^\s*(\d{3})\s*$/
681           or return { 'error' => "CVV2 (CVC2/CID) is three digits." };
682         $paycvv = $1;
683       }
684     }
685   
686   } else {
687     die "unknown payby $payby";
688   }
689
690   my %payby2fields = (
691     'CARD' => [ qw( paystart_month paystart_year payissue payip
692                     address1 address2 city state zip country    ) ],
693     'CHEK' => [ qw( ss paytype paystate stateid stateid_state payip ) ],
694   );
695
696   my $error = $cust_main->realtime_bop( $FS::payby::payby2bop{$payby}, $amount,
697     'quiet'    => 1,
698     'payinfo'  => $payinfo,
699     'paydate'  => $p->{'year'}. '-'. $p->{'month'}. '-01',
700     'payname'  => $payname,
701     'paybatch' => $paybatch, #this doesn't actually do anything
702     'paycvv'   => $paycvv,
703     'paynum_ref' => \$paynum,
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   my $receipt_html = '';
747   if($paynum) { 
748       # currently supported for realtime CC only; send receipt data to SS
749       my $cust_pay = qsearchs('cust_pay', { 'paynum' => $paynum } );
750       if($cust_pay) {
751         $receipt_html = qq!
752 <TABLE BGCOLOR="#cccccc" BORDER=0 CELLSPACING=2>
753
754 <TR>
755   <TD ALIGN="right">Payment#</TD>
756   <TD BGCOLOR="#FFFFFF"><B>! . $cust_pay->paynum . qq!</B></TD>
757 </TR>
758
759 <TR>
760   <TD ALIGN="right">Date</TD>
761
762   <TD BGCOLOR="#FFFFFF"><B>! . 
763         time2str("%a&nbsp;%b&nbsp;%o,&nbsp;%Y&nbsp;%r", $cust_pay->_date)
764                                                             . qq!</B></TD>
765 </TR>
766
767
768 <TR>
769   <TD ALIGN="right">Amount</TD>
770   <TD BGCOLOR="#FFFFFF"><B>! . $cust_pay->paid . qq!</B></TD>
771
772 </TR>
773
774 <TR>
775   <TD ALIGN="right">Payment method</TD>
776   <TD BGCOLOR="#FFFFFF"><B>! . $cust_pay->payby_name .' #'. $cust_pay->paymask
777                                                                 . qq!</B></TD>
778 </TR>
779
780 </TABLE>
781 !;
782       }
783   }
784
785   return { 'error' => '', 'receipt_html' => $receipt_html, };
786
787 }
788
789 sub realtime_collect {
790   my $p = shift;
791
792   my $session = _cache->get($p->{'session_id'})
793     or return { 'error' => "Can't resume session" }; #better error message
794
795   my $custnum = $session->{'custnum'};
796
797   my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
798     or return { 'error' => "unknown custnum $custnum" };
799
800   my $amount;
801   if ( $p->{'amount'} ) {
802     $amount = $p->{'amount'};
803   }
804   elsif ( $session->{'pkgnum'} ) {
805     $amount = $cust_main->balance_pkgnum( $session->{'pkgnum'} );
806   }
807   else {
808     $amount = $cust_main->balance;
809   }
810
811   my $error = $cust_main->realtime_collect(
812     'method'     => $p->{'method'},
813     'amount'     => $amount,
814     'pkgnum'     => $session->{'pkgnum'},
815     'session_id' => $p->{'session_id'},
816     'apply'      => 1,
817     'selfservice'=> 1,
818   );
819   return { 'error' => $error } unless ref( $error );
820
821   return { 'error' => '', amount => $amount, %$error };
822 }
823
824 sub process_payment_order_pkg {
825   my $p = shift;
826
827   my $hr = process_payment($p);
828   return $hr if $hr->{'error'};
829
830   order_pkg($p);
831 }
832
833 sub process_payment_order_renew {
834   my $p = shift;
835
836   my $hr = process_payment($p);
837   return $hr if $hr->{'error'};
838
839   order_renew($p);
840 }
841
842 sub process_prepay {
843
844   my $p = shift;
845
846   my $session = _cache->get($p->{'session_id'})
847     or return { 'error' => "Can't resume session" }; #better error message
848
849   my %return;
850
851   my $custnum = $session->{'custnum'};
852
853   my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
854     or return { 'error' => "unknown custnum $custnum" };
855
856   my( $amount, $seconds, $upbytes, $downbytes, $totalbytes ) = ( 0, 0, 0, 0, 0 );
857   my $error = $cust_main->recharge_prepay( $p->{'prepaid_cardnum'},
858                                            \$amount,
859                                            \$seconds,
860                                            \$upbytes,
861                                            \$downbytes,
862                                            \$totalbytes,
863                                          );
864
865   return { 'error' => $error } if $error;
866
867   return { 'error'     => '',
868            'amount'    => $amount,
869            'seconds'   => $seconds,
870            'duration'  => duration_exact($seconds),
871            'upbytes'   => $upbytes,
872            'upload'    => FS::UI::bytecount::bytecount_unexact($upbytes),
873            'downbytes' => $downbytes,
874            'download'  => FS::UI::bytecount::bytecount_unexact($downbytes),
875            'totalbytes'=> $totalbytes,
876            'totalload' => FS::UI::bytecount::bytecount_unexact($totalbytes),
877          };
878
879 }
880
881 sub invoice {
882   my $p = shift;
883   my $session = _cache->get($p->{'session_id'})
884     or return { 'error' => "Can't resume session" }; #better error message
885
886   my $custnum = $session->{'custnum'};
887
888   my $invnum = $p->{'invnum'};
889
890   my $cust_bill = qsearchs('cust_bill', { 'invnum'  => $invnum,
891                                           'custnum' => $custnum } )
892     or return { 'error' => "Can't find invnum" };
893
894   #my %return;
895
896   return { 'error'        => '',
897            'invnum'       => $invnum,
898            'invoice_text' => join('', $cust_bill->print_text ),
899            'invoice_html' => $cust_bill->print_html( { unsquelch_cdr => 1 } ),
900          };
901
902 }
903
904 sub invoice_logo {
905   my $p = shift;
906
907   #sessioning for this?  how do we get the session id to the backend invoice
908   # template so it can add it to the link, blah
909
910   my $agentnum = '';
911   if ( $p->{'invnum'} ) {
912     my $cust_bill = qsearchs('cust_bill', { 'invnum' => $p->{'invnum'} } )
913       or return { 'error' => 'unknown invnum' };
914     $agentnum = $cust_bill->cust_main->agentnum;
915   }
916
917   my $templatename = $p->{'template'} || $p->{'templatename'};
918
919   #false laziness-ish w/view/cust_bill-logo.cgi
920
921   my $conf = new FS::Conf;
922   if ( $templatename =~ /^([^\.\/]*)$/ && $conf->exists("logo_$1.png") ) {
923     $templatename = "_$1";
924   } else {
925     $templatename = '';
926   }
927
928   my $filename = "logo$templatename.png";
929
930   return { 'error'        => '',
931            'logo'         => $conf->config_binary($filename, $agentnum),
932            'content_type' => 'image/png', #should allow gif, jpg too
933          };
934 }
935
936
937 sub list_invoices {
938   my $p = shift;
939   my $session = _cache->get($p->{'session_id'})
940     or return { 'error' => "Can't resume session" }; #better error message
941
942   my $custnum = $session->{'custnum'};
943
944   my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
945     or return { 'error' => "unknown custnum $custnum" };
946
947   my @cust_bill = $cust_main->cust_bill;
948
949   return  { 'error'       => '',
950             'invoices'    =>  [ map { { 'invnum' => $_->invnum,
951                                         '_date'  => $_->_date,
952                                         'date'   => time2str("%b %o, %Y", $_->_date),
953                                       }
954                                     } @cust_bill
955                               ]
956           };
957 }
958
959 sub cancel {
960   my $p = shift;
961   my $session = _cache->get($p->{'session_id'})
962     or return { 'error' => "Can't resume session" }; #better error message
963
964   my $custnum = $session->{'custnum'};
965
966   my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
967     or return { 'error' => "unknown custnum $custnum" };
968
969   my @errors = $cust_main->cancel( 'quiet'=>1 );
970
971   my $error = scalar(@errors) ? join(' / ', @errors) : '';
972
973   return { 'error' => $error };
974
975 }
976
977 sub list_pkgs {
978   my $p = shift;
979
980   my($context, $session, $custnum) = _custoragent_session_custnum($p);
981   return { 'error' => $session } if $context eq 'error';
982
983   my $search = { 'custnum' => $custnum };
984   $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
985   my $cust_main = qsearchs('cust_main', $search )
986     or return { 'error' => "unknown custnum $custnum" };
987
988   my $conf = new FS::Conf;
989   
990 # the duplication below is necessary:
991 # 1. to maintain the current buggy behaviour wrt the cust_pkg and part_pkg
992 # hashes overwriting each other (setup and no_auto fields). Fixing that is a
993 # non-backwards-compatible change breaking the software of anyone using the API
994 # instead of the stock selfservice
995 # 2. to return cancelled packages as well - for wholesale and non-wholesale
996   if( $conf->exists('selfservice_server-view-wholesale') ) {
997     return { 'svcnum'   => $session->{'svcnum'},
998             'custnum'  => $custnum,
999             'cust_pkg' => [ map {
1000                           { $_->hash,
1001                             part_pkg => [ map $_->hashref, $_->part_pkg ],
1002                             part_svc =>
1003                               [ map $_->hashref, $_->available_part_svc ],
1004                             cust_svc => 
1005                               [ map { my $ref = { $_->hash,
1006                                                   label => [ $_->label ],
1007                                                 };
1008                                       $ref->{_password} = $_->svc_x->_password
1009                                         if $context eq 'agent'
1010                                         && $conf->exists('agent-showpasswords')
1011                                         && $_->part_svc->svcdb eq 'svc_acct';
1012                                       $ref;
1013                                     } $_->cust_svc
1014                               ],
1015                           };
1016                         } $cust_main->cust_pkg
1017                   ],
1018     'small_custview' =>
1019       small_custview( $cust_main, $conf->config('countrydefault') ),
1020     'wholesale_view' => 1,
1021     'login_svcpart' => [ $conf->config('selfservice_server-login_svcpart') ],
1022     'date_format' => $conf->config('date_format') || '%m/%d/%Y',
1023     'lnp' => $conf->exists('svc_phone-lnp'),
1024       };
1025   }
1026
1027   { 'svcnum'   => $session->{'svcnum'},
1028     'custnum'  => $custnum,
1029     'cust_pkg' => [ map {
1030                           { $_->hash,
1031                             $_->part_pkg->hash,
1032                             part_svc =>
1033                               [ map $_->hashref, $_->available_part_svc ],
1034                             cust_svc => 
1035                               [ map { my $ref = { $_->hash,
1036                                                   label => [ $_->label ],
1037                                                 };
1038                                       $ref->{_password} = $_->svc_x->_password
1039                                         if $context eq 'agent'
1040                                         && $conf->exists('agent-showpasswords')
1041                                         && $_->part_svc->svcdb eq 'svc_acct';
1042                                       $ref;
1043                                     } $_->cust_svc
1044                               ],
1045                           };
1046                         } $cust_main->ncancelled_pkgs
1047                   ],
1048     'small_custview' =>
1049       small_custview( $cust_main, $conf->config('countrydefault') ),
1050   };
1051
1052 }
1053
1054 sub list_svcs {
1055   my $p = shift;
1056
1057   my($context, $session, $custnum) = _custoragent_session_custnum($p);
1058   return { 'error' => $session } if $context eq 'error';
1059
1060   my $search = { 'custnum' => $custnum };
1061   $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
1062   my $cust_main = qsearchs('cust_main', $search )
1063     or return { 'error' => "unknown custnum $custnum" };
1064
1065   my @cust_svc = ();
1066   #foreach my $cust_pkg ( $cust_main->ncancelled_pkgs ) {
1067   foreach my $cust_pkg ( $p->{'ncancelled'} 
1068                          ? $cust_main->ncancelled_pkgs
1069                          : $cust_main->unsuspended_pkgs ) {
1070     next if $session->{'pkgnum'} && $cust_pkg->pkgnum != $session->{'pkgnum'};
1071     push @cust_svc, @{[ $cust_pkg->cust_svc ]}; #@{[ ]} to force array context
1072   }
1073   if ( $p->{'svcdb'} ) {
1074     my $svcdb = ref($p->{'svcdb'}) eq 'HASH'
1075                   ? $p->{'svcdb'}
1076                   : ref($p->{'svcdb'}) eq 'ARRAY'
1077                     ? { map { $_=>1 } @{ $p->{'svcdb'} } }
1078                     : { $p->{'svcdb'} => 1 };
1079     @cust_svc = grep $svcdb->{ $_->part_svc->svcdb }, @cust_svc
1080   }
1081
1082   #@svc_x = sort { $a->domain cmp $b->domain || $a->username cmp $b->username }
1083   #              @svc_x;
1084
1085   { 
1086     'svcnum'   => $session->{'svcnum'},
1087     'custnum'  => $custnum,
1088     'view_usage_nodomain' => $conf->exists('selfservice-view_usage_nodomain'),
1089     'svcs'     => [
1090       map { 
1091             my $svc_x = $_->svc_x;
1092             my($label, $value) = $_->label;
1093             my $svcdb = $_->part_svc->svcdb;
1094             my $part_pkg = $_->cust_pkg->part_pkg;
1095
1096             my %hash = (
1097               'svcnum' => $_->svcnum,
1098               'svcdb'  => $svcdb,
1099               'label'  => $label,
1100               'value'  => $value,
1101             );
1102
1103             if ( $svcdb eq 'svc_acct' ) {
1104               %hash = (
1105                 %hash,
1106                 'username'   => $svc_x->username,
1107                 'email'      => $svc_x->email,
1108                 'seconds'    => $svc_x->seconds,
1109                 'upbytes'    => display_bytecount($svc_x->upbytes),
1110                 'downbytes'  => display_bytecount($svc_x->downbytes),
1111                 'totalbytes' => display_bytecount($svc_x->totalbytes),
1112
1113                 'recharge_amount'  => $part_pkg->option('recharge_amount',1),
1114                 'recharge_seconds' => $part_pkg->option('recharge_seconds',1),
1115                 'recharge_upbytes'    =>
1116                   display_bytecount($part_pkg->option('recharge_upbytes',1)),
1117                 'recharge_downbytes'  =>
1118                   display_bytecount($part_pkg->option('recharge_downbytes',1)),
1119                 'recharge_totalbytes' =>
1120                   display_bytecount($part_pkg->option('recharge_totalbytes',1)),
1121                 # more...
1122               );
1123
1124             } elsif ( $svcdb eq 'svc_phone' ) {
1125               %hash = (
1126                 %hash,
1127               );
1128             }
1129
1130             \%hash;
1131           }
1132           @cust_svc
1133     ],
1134   };
1135
1136 }
1137
1138 sub _list_svc_usage {
1139   my($svc_acct, $begin, $end) = @_;
1140   my @usage = ();
1141   foreach my $part_export ( 
1142     map { qsearch ( 'part_export', { 'exporttype' => $_ } ) }
1143     qw( sqlradius sqlradius_withdomain )
1144   ) {
1145     push @usage, @ { $part_export->usage_sessions($begin, $end, $svc_acct) };
1146   }
1147   (@usage);
1148 }
1149
1150 sub list_svc_usage {
1151   _usage_details(\&_list_svc_usage, @_);
1152 }
1153
1154 sub _list_support_usage {
1155   my($svc_acct, $begin, $end) = @_;
1156   my @usage = ();
1157   foreach ( grep { $begin <= $_->_date && $_->_date <= $end }
1158             qsearch('acct_rt_transaction', { 'svcnum' => $svc_acct->svcnum })
1159           ) {
1160     push @usage, { 'seconds'  => $_->seconds,
1161                    'support'  => $_->support,
1162                    '_date'    => $_->_date,
1163                    'id'       => $_->transaction_id,
1164                    'creator'  => $_->creator,
1165                    'subject'  => $_->subject,
1166                    'status'   => $_->status,
1167                    'ticketid' => $_->ticketid,
1168                  };
1169   }
1170   (@usage);
1171 }
1172
1173 sub list_support_usage {
1174   _usage_details(\&_list_support_usage, @_);
1175 }
1176
1177 sub _list_cdr_usage {
1178   my($svc_phone, $begin, $end) = @_;
1179   map [ $_->downstream_csv('format' => 'default', 'keeparray' => 1) ], #XXX config for format
1180                        $svc_phone->get_cdrs( 'begin'=>$begin, 'end'=>$end, );
1181 }
1182
1183 sub list_cdr_usage {
1184   my $p = shift;
1185   _usage_details( \&_list_cdr_usage, $p,
1186                   'svcdb' => 'svc_phone',
1187                 );
1188 }
1189
1190 sub _usage_details {
1191   my($callback, $p, %opt) = @_;
1192
1193   my($context, $session, $custnum) = _custoragent_session_custnum($p);
1194   return { 'error' => $session } if $context eq 'error';
1195
1196   my $search = { 'svcnum' => $p->{'svcnum'} };
1197   $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
1198
1199   my $svcdb = $opt{'svcdb'} || 'svc_acct';
1200
1201   my $svc_x = qsearchs( $svcdb, $search );
1202   return { 'error' => 'No service selected in list_svc_usage' } 
1203     unless $svc_x;
1204
1205   my $header = $svcdb eq 'svc_phone'
1206                  ? [ split(',', FS::cdr::invoice_header('default') ) ]  #XXX
1207                  : [];
1208
1209   my $cust_pkg = $svc_x->cust_svc->cust_pkg;
1210   my $freq     = $cust_pkg->part_pkg->freq;
1211   my $start    = $cust_pkg->setup;
1212   #my $end      = $cust_pkg->bill; # or time?
1213   my $end      = time;
1214
1215   unless ( $p->{beginning} ) {
1216     $p->{beginning} = $cust_pkg->last_bill;
1217     $p->{ending}    = $end;
1218   }
1219
1220   my (@usage) = &$callback($svc_x, $p->{beginning}, $p->{ending});
1221
1222   #kinda false laziness with FS::cust_main::bill, but perhaps
1223   #we should really change this bit to DateTime and DateTime::Duration
1224   #
1225   #change this bit to use Date::Manip? CAREFUL with timezones (see
1226   # mailing list archive)
1227   my ($nsec,$nmin,$nhour,$nmday,$nmon,$nyear) =
1228     (localtime($p->{ending}) )[0,1,2,3,4,5];
1229   my ($psec,$pmin,$phour,$pmday,$pmon,$pyear) =
1230     (localtime($p->{beginning}) )[0,1,2,3,4,5];
1231
1232   if ( $freq =~ /^\d+$/ ) {
1233     $nmon += $freq;
1234     until ( $nmon < 12 ) { $nmon -= 12; $nyear++; }
1235     $pmon -= $freq;
1236     until ( $pmon >= 0 ) { $pmon += 12; $pyear--; }
1237   } elsif ( $freq =~ /^(\d+)w$/ ) {
1238     my $weeks = $1;
1239     $nmday += $weeks * 7;
1240     $pmday -= $weeks * 7;
1241   } elsif ( $freq =~ /^(\d+)d$/ ) {
1242     my $days = $1;
1243     $nmday += $days;
1244     $pmday -= $days;
1245   } elsif ( $freq =~ /^(\d+)h$/ ) {
1246     my $hours = $1;
1247     $nhour += $hours;
1248     $phour -= $hours;
1249   } else {
1250     return { 'error' => "unparsable frequency: ". $freq };
1251   }
1252   
1253   my $previous  = timelocal_nocheck($psec,$pmin,$phour,$pmday,$pmon,$pyear);
1254   my $next      = timelocal_nocheck($nsec,$nmin,$nhour,$nmday,$nmon,$nyear);
1255
1256   { 
1257     'error'     => '',
1258     'svcnum'    => $p->{svcnum},
1259     'beginning' => $p->{beginning},
1260     'ending'    => $p->{ending},
1261     'previous'  => ($previous > $start) ? $previous : $start,
1262     'next'      => ($next < $end) ? $next : $end,
1263     'header'    => $header,
1264     'usage'     => \@usage,
1265   };
1266 }
1267
1268 sub order_pkg {
1269   my $p = shift;
1270
1271   my($context, $session, $custnum) = _custoragent_session_custnum($p);
1272   return { 'error' => $session } if $context eq 'error';
1273
1274   my $search = { 'custnum' => $custnum };
1275   $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
1276   my $cust_main = qsearchs('cust_main', $search )
1277     or return { 'error' => "unknown custnum $custnum" };
1278
1279   my $status = $cust_main->status;
1280   #false laziness w/ClientAPI/Signup.pm
1281
1282   my $cust_pkg = new FS::cust_pkg ( {
1283     'custnum' => $custnum,
1284     'pkgpart' => $p->{'pkgpart'},
1285   } );
1286   my $error = $cust_pkg->check;
1287   return { 'error' => $error } if $error;
1288
1289   my @svc = ();
1290   unless ( $p->{'svcpart'} eq 'none' ) {
1291
1292     my $svcdb;
1293     my $svcpart = '';
1294     if ( $p->{'svcpart'} =~ /^(\d+)$/ ) {
1295       $svcpart = $1;
1296       my $part_svc = qsearchs('part_svc', { 'svcpart' => $svcpart } );
1297       return { 'error' => "Unknown svcpart $svcpart" } unless $part_svc;
1298       $svcdb = $part_svc->svcdb;
1299     } else {
1300       $svcdb = 'svc_acct';
1301     }
1302     $svcpart ||= $cust_pkg->part_pkg->svcpart($svcdb);
1303
1304     my %fields = (
1305       'svc_acct'     => [ qw( username domsvc _password sec_phrase popnum ) ],
1306       'svc_domain'   => [ qw( domain ) ],
1307       'svc_phone'    => [ qw( phonenum pin sip_password phone_name ) ],
1308       'svc_external' => [ qw( id title ) ],
1309       'svc_pbx'      => [ qw( id name ) ],
1310     );
1311   
1312     my $svc_x = "FS::$svcdb"->new( {
1313       'svcpart'   => $svcpart,
1314       map { $_ => $p->{$_} } @{$fields{$svcdb}}
1315     } );
1316     
1317     if ( $svcdb eq 'svc_acct' && exists($p->{"snarf_machine1"}) ) {
1318       my @acct_snarf;
1319       my $snarfnum = 1;
1320       while ( length($p->{"snarf_machine$snarfnum"}) ) {
1321         my $acct_snarf = new FS::acct_snarf ( {
1322           'machine'   => $p->{"snarf_machine$snarfnum"},
1323           'protocol'  => $p->{"snarf_protocol$snarfnum"},
1324           'username'  => $p->{"snarf_username$snarfnum"},
1325           '_password' => $p->{"snarf_password$snarfnum"},
1326         } );
1327         $snarfnum++;
1328         push @acct_snarf, $acct_snarf;
1329       }
1330       $svc_x->child_objects( \@acct_snarf );
1331     }
1332     
1333     my $y = $svc_x->setdefault; # arguably should be in new method
1334     return { 'error' => $y } if $y && !ref($y);
1335   
1336     $error = $svc_x->check;
1337     return { 'error' => $error } if $error;
1338
1339     push @svc, $svc_x;
1340
1341   }
1342
1343   use Tie::RefHash;
1344   tie my %hash, 'Tie::RefHash';
1345   %hash = ( $cust_pkg => \@svc );
1346   #msgcat
1347   $error = $cust_main->order_pkgs( \%hash, 'noexport' => 1 );
1348   return { 'error' => $error } if $error;
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       $cust_pkg->cancel('quiet'=>1);
1357       return $bill_error;
1358     } else {
1359       $cust_pkg->reexport;
1360     }
1361
1362   } else {
1363     $cust_pkg->reexport;
1364   }
1365
1366   my $svcnum = $svc[0] ? $svc[0]->svcnum : '';
1367
1368   return { error=>'', pkgnum=>$cust_pkg->pkgnum, svcnum=>$svcnum };
1369
1370 }
1371
1372 sub change_pkg {
1373   my $p = shift;
1374
1375   my($context, $session, $custnum) = _custoragent_session_custnum($p);
1376   return { 'error' => $session } if $context eq 'error';
1377
1378   my $search = { 'custnum' => $custnum };
1379   $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
1380   my $cust_main = qsearchs('cust_main', $search )
1381     or return { 'error' => "unknown custnum $custnum" };
1382
1383   my $status = $cust_main->status;
1384   my $cust_pkg = qsearchs('cust_pkg', { 'pkgnum' => $p->{pkgnum} } )
1385     or return { 'error' => "unknown package $p->{pkgnum}" };
1386
1387   my @newpkg;
1388   my $error = FS::cust_pkg::order( $custnum,
1389                                    [$p->{pkgpart}],
1390                                    [$p->{pkgnum}],
1391                                    \@newpkg,
1392                                  );
1393
1394   my $conf = new FS::Conf;
1395   if ( $conf->exists('signup_server-realtime') ) {
1396
1397     my $bill_error = _do_bop_realtime( $cust_main, $status );
1398
1399     if ($bill_error) {
1400       $newpkg[0]->suspend;
1401       return $bill_error;
1402     } else {
1403       $newpkg[0]->reexport;
1404     }
1405
1406   } else {  
1407     $newpkg[0]->reexport;
1408   }
1409
1410   return { error => '', pkgnum => $cust_pkg->pkgnum };
1411
1412 }
1413
1414 sub order_recharge {
1415   my $p = shift;
1416
1417   my($context, $session, $custnum) = _custoragent_session_custnum($p);
1418   return { 'error' => $session } if $context eq 'error';
1419
1420   my $search = { 'custnum' => $custnum };
1421   $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
1422   my $cust_main = qsearchs('cust_main', $search )
1423     or return { 'error' => "unknown custnum $custnum" };
1424
1425   my $status = $cust_main->status;
1426   my $cust_svc = qsearchs( 'cust_svc', { 'svcnum' => $p->{'svcnum'} } )
1427     or return { 'error' => "unknown service " . $p->{'svcnum'} };
1428
1429   my $svc_x = $cust_svc->svc_x;
1430   my $part_pkg = $cust_svc->cust_pkg->part_pkg;
1431
1432   my %vhash =
1433     map { $_ =~ /^recharge_(.*)$/; $1, $part_pkg->option($_, 1) } 
1434     qw ( recharge_seconds recharge_upbytes recharge_downbytes
1435          recharge_totalbytes );
1436   my $amount = $part_pkg->option('recharge_amount', 1); 
1437   
1438   my ($l, $v, $d) = $cust_svc->label;  # blah
1439   my $pkg = "Recharge $v"; 
1440
1441   my $bill_error = $cust_main->charge($amount, $pkg,
1442      "time: $vhash{seconds}, up: $vhash{upbytes}," . 
1443      "down: $vhash{downbytes}, total: $vhash{totalbytes}",
1444      $part_pkg->taxclass); #meh
1445
1446   my $conf = new FS::Conf;
1447   if ( $conf->exists('signup_server-realtime') && !$bill_error ) {
1448
1449     $bill_error = _do_bop_realtime( $cust_main, $status );
1450
1451     if ($bill_error) {
1452       return $bill_error;
1453     } else {
1454       my $error = $svc_x->recharge (\%vhash);
1455       return { 'error' => $error } if $error;
1456     }
1457
1458   } else {  
1459     my $error = $bill_error;
1460     $error ||= $svc_x->recharge (\%vhash);
1461     return { 'error' => $error } if $error;
1462   }
1463
1464   return { error => '', svc => $cust_svc->part_svc->svc };
1465
1466 }
1467
1468 sub _do_bop_realtime {
1469   my ($cust_main, $status) = (shift, shift);
1470
1471     my $old_balance = $cust_main->balance;
1472
1473     my $bill_error =    $cust_main->bill
1474                      || $cust_main->apply_payments_and_credits
1475                      || $cust_main->realtime_collect('selfservice' => 1);
1476
1477     if (    $cust_main->balance > $old_balance
1478          && $cust_main->balance > 0
1479          && ( $cust_main->payby !~ /^(BILL|DCRD|DCHK)$/ ?
1480               1 : $status eq 'suspended' ) ) {
1481       #this makes sense.  credit is "un-doing" the invoice
1482       my $conf = new FS::Conf;
1483       $cust_main->credit( sprintf("%.2f", $cust_main->balance - $old_balance ),
1484                           'self-service decline',
1485                           'reason_type' => $conf->config('signup_credit_type'),
1486                         );
1487       $cust_main->apply_credits( 'order' => 'newest' );
1488
1489       return { 'error' => '_decline', 'bill_error' => $bill_error };
1490     }
1491
1492     '';
1493 }
1494
1495 sub renew_info {
1496   my $p = shift;
1497
1498   my($context, $session, $custnum) = _custoragent_session_custnum($p);
1499   return { 'error' => $session } if $context eq 'error';
1500
1501   my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1502     or return { 'error' => "unknown custnum $custnum" };
1503
1504   my @cust_pkg = sort { $a->bill <=> $b->bill }
1505                  grep { $_->part_pkg->freq ne '0' }
1506                  $cust_main->ncancelled_pkgs;
1507
1508   #return { 'error' => 'No active packages to renew.' } unless @cust_pkg;
1509
1510   my $total = $cust_main->balance;
1511
1512   my @array = map {
1513                     my $bill = $_->bill;
1514                     $total += $_->part_pkg->base_recur($_, \$bill);
1515                     my $renew_date = $_->part_pkg->add_freq($_->bill);
1516                     {
1517                       'pkgnum'             => $_->pkgnum,
1518                       'amount'             => sprintf('%.2f', $total),
1519                       'bill_date'          => $_->bill,
1520                       'bill_date_pretty'   => time2str('%x', $_->bill),
1521                       'renew_date'         => $renew_date,
1522                       'renew_date_pretty'  => time2str('%x', $renew_date),
1523                       'expire_date'        => $_->expire,
1524                       'expire_date_pretty' => time2str('%x', $_->expire),
1525                     };
1526                   }
1527                   @cust_pkg;
1528
1529   return { 'dates' => \@array };
1530
1531 }
1532
1533 sub payment_info_renew_info {
1534   my $p = shift;
1535   my $renew_info   = renew_info($p);
1536   my $payment_info = payment_info($p);
1537   return { %$renew_info,
1538            %$payment_info,
1539          };
1540 }
1541
1542 sub order_renew {
1543   my $p = shift;
1544
1545   my($context, $session, $custnum) = _custoragent_session_custnum($p);
1546   return { 'error' => $session } if $context eq 'error';
1547
1548   my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1549     or return { 'error' => "unknown custnum $custnum" };
1550
1551   my $date = $p->{'date'};
1552
1553   my $now = time;
1554
1555   #freeside-daily -n -d $date fs_daily $custnum
1556   $cust_main->bill_and_collect( 'time'         => $date,
1557                                 'invoice_time' => $now,
1558                                 'actual_time'  => $now,
1559                                 'check_freq'   => '1d',
1560                               );
1561
1562   return { 'error' => '' };
1563
1564 }
1565
1566 # these are basically the same
1567 sub cancel_pkg    { alter_pkg(shift, 'cancel', 'quiet' => 1) }
1568 sub suspend_pkg   { 
1569   my $conf = new FS::Conf;
1570   my $reasonnum = $conf->config('selfservice-self_suspend_reason')
1571     or return { 'error' => "Permission denied" };
1572   alter_pkg(shift, 'suspend', 'reason' => $reasonnum) 
1573 }
1574
1575 sub alter_pkg {
1576   my $p = shift;
1577   my $method = shift;
1578   my $session = _cache->get($p->{'session_id'})
1579     or return { 'error' => "Can't resume session" }; #better error message
1580
1581   my $custnum = $session->{'custnum'};
1582
1583   my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1584     or return { 'error' => "unknown custnum $custnum" };
1585
1586   my $pkgnum = $p->{'pkgnum'};
1587
1588   my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
1589                                         'pkgnum'  => $pkgnum,   } )
1590     or return { 'error' => "unknown pkgnum $pkgnum" };
1591
1592   my $error = $cust_pkg->$method(@_);
1593   return { 'error' => $error };
1594
1595 }
1596
1597 sub provision_phone {
1598  my $p = shift;
1599  my @bulkdid;
1600  @bulkdid = @{$p->{'bulkdid'}} if $p->{'bulkdid'};
1601
1602 # single DID LNP
1603  unless($p->{'lnp'}) {
1604     $p->{'lnp_desired_due_date'} = parse_datetime($p->{'lnp_desired_due_date'});
1605     $p->{'lnp_status'} = "portingin";
1606     return _provision( 'FS::svc_phone',
1607                   [qw(lnp_desired_due_date lnp_other_provider 
1608                     lnp_other_provider_account phonenum countrycode lnp_status)],
1609                   [qw(phonenum countrycode)],
1610                   $p,
1611                   @_
1612                 );
1613  }
1614
1615 # single DID order
1616  unless (scalar(@bulkdid)) {
1617     return _provision( 'FS::svc_phone',
1618                   [qw(phonenum countrycode)],
1619                   [qw(phonenum countrycode)],
1620                   $p,
1621                   @_
1622                 );
1623  }
1624
1625 # bulk DID order case
1626   my $error;
1627   foreach my $did ( @bulkdid ) {
1628     $did =~ s/[^0-9]//g;
1629     $error = _provision( 'FS::svc_phone',
1630               [qw(phonenum countrycode)],
1631               [qw(phonenum countrycode)],
1632               {
1633                 'pkgnum' => $p->{'pkgnum'},
1634                 'svcpart' => $p->{'svcpart'},
1635                 'phonenum' => $did,
1636                 'countrycode' => $p->{'countrycode'},
1637                 'session_id' => $p->{'session_id'},
1638               }
1639             );
1640     return $error if ($error->{'error'} && length($error->{'error'}) > 1);
1641   }
1642   { 'bulkdid' => [ @bulkdid ], 'svc' => $error->{'svc'} }
1643 }
1644
1645 sub provision_acct {
1646   my $p = shift;
1647   warn "provision_acct called\n"
1648     if $DEBUG;
1649
1650   return { 'error' => gettext('passwords_dont_match') }
1651     if $p->{'_password'} ne $p->{'_password2'};
1652   return { 'error' => gettext('empty_password') }
1653     unless length($p->{'_password'});
1654  
1655   if ($p->{'domsvc'}) {
1656     my %domains = domain_select_hash FS::svc_acct(map { $_ => $p->{$_} }
1657                                                   qw ( svcpart pkgnum ) );
1658     return { 'error' => gettext('invalid_domain') }
1659       unless ($domains{$p->{'domsvc'}});
1660   }
1661
1662   warn "provision_acct calling _provision\n"
1663     if $DEBUG;
1664   _provision( 'FS::svc_acct',
1665               [qw(username _password domsvc)],
1666               [qw(username _password domsvc)],
1667               $p,
1668               @_
1669             );
1670 }
1671
1672 sub provision_external {
1673   my $p = shift;
1674   #_provision( 'FS::svc_external', [qw(id title)], [qw(id title)], $p, @_ );
1675   _provision( 'FS::svc_external',
1676               [],
1677               [qw(id title)],
1678               $p,
1679               @_
1680             );
1681 }
1682
1683 sub _provision {
1684   my( $class, $fields, $return_fields, $p ) = splice(@_, 0, 4);
1685   warn "_provision called for $class\n"
1686     if $DEBUG;
1687
1688   my($context, $session, $custnum) = _custoragent_session_custnum($p);
1689   return { 'error' => $session } if $context eq 'error';
1690
1691   my $search = { 'custnum' => $custnum };
1692   $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
1693   my $cust_main = qsearchs('cust_main', $search )
1694     or return { 'error' => "unknown custnum $custnum" };
1695
1696   my $pkgnum = $p->{'pkgnum'};
1697
1698   warn "searching for custnum $custnum pkgnum $pkgnum\n"
1699     if $DEBUG;
1700   my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
1701                                         'pkgnum'  => $pkgnum,
1702                                                                } )
1703     or return { 'error' => "unknown pkgnum $pkgnum" };
1704
1705   warn "searching for svcpart ". $p->{'svcpart'}. "\n"
1706     if $DEBUG;
1707   my $part_svc = qsearchs('part_svc', { 'svcpart' => $p->{'svcpart'} } )
1708     or return { 'error' => "unknown svcpart $p->{'svcpart'}" };
1709
1710   warn "creating $class record\n"
1711     if $DEBUG;
1712   my $svc_x = $class->new( {
1713     'pkgnum'  => $p->{'pkgnum'},
1714     'svcpart' => $p->{'svcpart'},
1715     map { $_ => $p->{$_} } @$fields
1716   } );
1717   warn "inserting $class record\n"
1718     if $DEBUG;
1719   my $error = $svc_x->insert;
1720
1721   unless ( $error ) {
1722     warn "finding inserted record for svcnum ". $svc_x->svcnum. "\n"
1723       if $DEBUG;
1724     $svc_x = qsearchs($svc_x->table, { 'svcnum' => $svc_x->svcnum })
1725   }
1726
1727   my $return = { 'svc'   => $part_svc->svc,
1728                  'error' => $error,
1729                  map { $_ => $svc_x->get($_) } @$return_fields
1730                };
1731   warn "_provision returning ". Dumper($return). "\n"
1732     if $DEBUG;
1733   return $return;
1734
1735 }
1736
1737 sub part_svc_info {
1738   my $p = shift;
1739
1740   my($context, $session, $custnum) = _custoragent_session_custnum($p);
1741   return { 'error' => $session } if $context eq 'error';
1742
1743   my $search = { 'custnum' => $custnum };
1744   $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
1745   my $cust_main = qsearchs('cust_main', $search )
1746     or return { 'error' => "unknown custnum $custnum" };
1747
1748   my $pkgnum = $p->{'pkgnum'};
1749
1750   my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
1751                                         'pkgnum'  => $pkgnum,
1752                                                                } )
1753     or return { 'error' => "unknown pkgnum $pkgnum" };
1754
1755   my $svcpart = $p->{'svcpart'};
1756
1757   my $pkg_svc = qsearchs('pkg_svc', { 'pkgpart' => $cust_pkg->pkgpart,
1758                                       'svcpart' => $svcpart,           } )
1759     or return { 'error' => "unknown svcpart $svcpart for pkgnum $pkgnum" };
1760   my $part_svc = $pkg_svc->part_svc;
1761
1762   my $conf = new FS::Conf;
1763
1764   return {
1765     'svc'     => $part_svc->svc,
1766     'svcdb'   => $part_svc->svcdb,
1767     'pkgnum'  => $pkgnum,
1768     'svcpart' => $svcpart,
1769     'custnum' => $custnum,
1770
1771     'security_phrase' => 0, #XXX !
1772     'svc_acct_pop'    => [], #XXX !
1773     'popnum'          => '',
1774     'init_popstate'   => '',
1775     'popac'           => '',
1776     'acstate'         => '',
1777
1778     'small_custview' =>
1779       small_custview( $cust_main, $conf->config('countrydefault') ),
1780
1781   };
1782
1783 }
1784
1785 sub unprovision_svc {
1786   my $p = shift;
1787
1788   my($context, $session, $custnum) = _custoragent_session_custnum($p);
1789   return { 'error' => $session } if $context eq 'error';
1790
1791   my $search = { 'custnum' => $custnum };
1792   $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
1793   my $cust_main = qsearchs('cust_main', $search )
1794     or return { 'error' => "unknown custnum $custnum" };
1795
1796   my $svcnum = $p->{'svcnum'};
1797
1798   my $cust_svc = qsearchs('cust_svc', { 'svcnum'  => $svcnum, } )
1799     or return { 'error' => "unknown svcnum $svcnum" };
1800
1801   return { 'error' => "Service $svcnum does not belong to customer $custnum" }
1802     unless $cust_svc->cust_pkg->custnum == $custnum;
1803
1804   my $conf = new FS::Conf;
1805
1806   return { 'svc'   => $cust_svc->part_svc->svc,
1807            'error' => $cust_svc->cancel,
1808            'small_custview' =>
1809              small_custview( $cust_main, $conf->config('countrydefault') ),
1810          };
1811
1812 }
1813
1814 sub myaccount_passwd {
1815   my $p = shift;
1816   my($context, $session, $custnum) = _custoragent_session_custnum($p);
1817   return { 'error' => $session } if $context eq 'error';
1818
1819   return { 'error' => "New passwords don't match." }
1820     if $p->{'new_password'} ne $p->{'new_password2'};
1821
1822   return { 'error' => 'Enter new password' }
1823     unless length($p->{'new_password'});
1824
1825   #my $search = { 'custnum' => $custnum };
1826   #$search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
1827   $custnum =~ /^(\d+)$/ or die "illegal custnum";
1828   my $search = " AND custnum = $1";
1829   $search .= " AND agentnum = ". $session->{'agentnum'} if $context eq 'agent';
1830
1831   my $svc_acct = qsearchs( {
1832     'table'     => 'svc_acct',
1833     'addl_from' => 'LEFT JOIN cust_svc  USING ( svcnum  ) '.
1834                    'LEFT JOIN cust_pkg  USING ( pkgnum  ) '.
1835                    'LEFT JOIN cust_main USING ( custnum ) ',
1836     'hashref'   => { 'svcnum' => $p->{'svcnum'}, },
1837     'extra_sql' => $search, #important
1838   } )
1839     or return { 'error' => "Service not found" };
1840
1841   $svc_acct->_password($p->{'new_password'});
1842   my $error = $svc_acct->replace();
1843
1844   my($label, $value) = $svc_acct->cust_svc->label;
1845
1846   return { 'error' => $error,
1847            'label' => $label,
1848            'value' => $value,
1849          };
1850
1851 }
1852
1853 sub create_ticket {
1854   my $p = shift;
1855   my($context, $session, $custnum) = _custoragent_session_custnum($p);
1856   return { 'error' => $session } if $context eq 'error';
1857
1858   warn "$me create_ticket: initializing ticket system\n" if $DEBUG;
1859   FS::TicketSystem->init();
1860
1861   my $conf = new FS::Conf;
1862   my $queue = $p->{'queue'}
1863               || $conf->config('ticket_system-selfservice_queueid')
1864               || $conf->config('ticket_system-default_queueid');
1865
1866   warn "$me create_ticket: creating ticket\n" if $DEBUG;
1867   my $err_or_ticket = FS::TicketSystem->create_ticket(
1868     '', #create RT session based on FS CurrentUser (fs_selfservice)
1869     'queue'   => $queue,
1870     'custnum' => $custnum,
1871     'svcnum'  => $session->{'svcnum'},
1872     map { $_ => $p->{$_} } qw( requestor cc subject message mime_type )
1873   );
1874
1875   if ( ref($err_or_ticket) ) {
1876     warn "$me create_ticket: sucessful: ". $err_or_ticket->id. "\n"
1877       if $DEBUG;
1878     return { 'error'     => '',
1879              'ticket_id' => $err_or_ticket->id,
1880            };
1881   } else {
1882     warn "$me create_ticket: unsucessful: $err_or_ticket\n"
1883       if $DEBUG;
1884     return { 'error' => $err_or_ticket };
1885   }
1886
1887
1888 }
1889
1890 sub did_report {
1891   my $p = shift;
1892   my($context, $session, $custnum) = _custoragent_session_custnum($p);
1893   return { 'error' => $session } if $context eq 'error';
1894  
1895   return { error => 'requested format not implemented' } 
1896     unless ($p->{'format'} eq 'csv' || $p->{'format'} eq 'xls');
1897
1898   my $conf = new FS::Conf;
1899   my $age_threshold = 0;
1900   $age_threshold = time() - $conf->config('selfservice-recent-did-age')
1901     if ($p->{'recentonly'} && $conf->exists('selfservice-recent-did-age'));
1902
1903   my $search = { 'custnum' => $custnum };
1904   $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
1905   my $cust_main = qsearchs('cust_main', $search )
1906     or return { 'error' => "unknown custnum $custnum" };
1907
1908 # does it make more sense to just run one sql query for this instead of all the
1909 # insanity below? would increase performance greately for large data sets?
1910   my @svc_phone = ();
1911   foreach my $cust_pkg ( $cust_main->ncancelled_pkgs ) {
1912         my @part_svc = $cust_pkg->part_svc;
1913         foreach my $part_svc ( @part_svc ) {
1914             if($part_svc->svcdb eq 'svc_phone'){
1915                 my @cust_pkg_svc = @{$part_svc->cust_pkg_svc};
1916                 foreach my $cust_pkg_svc ( @cust_pkg_svc ) {
1917                     push @svc_phone, $cust_pkg_svc->svc_x
1918                         if $cust_pkg_svc->date_inserted >= $age_threshold;
1919                 }
1920             }
1921         }
1922   }
1923
1924   my $csv;
1925   my $xls;
1926   my($xls_r,$xls_c) = (0,0);
1927   my $xls_workbook;
1928   my $content = '';
1929   my @fields = qw( countrycode phonenum pin sip_password phone_name );
1930   if($p->{'format'} eq 'csv') {
1931     $csv = new Text::CSV_XS { 'always_quote' => 1,
1932                                  'eol'          => "\n",
1933                                 };
1934     return { 'error' => 'Unable to create CSV' } unless $csv->combine(@fields);
1935     $content .= $csv->string;
1936   }
1937   elsif($p->{'format'} eq 'xls') {
1938     my $XLS1 = new IO::Scalar \$content;
1939     $xls_workbook = Spreadsheet::WriteExcel->new($XLS1) 
1940         or return { 'error' => "Error opening .xls file: $!" };
1941     $xls = $xls_workbook->add_worksheet('DIDs');
1942     foreach ( @fields ) {
1943         $xls->write(0,$xls_c++,$_);
1944     }
1945     $xls_r++;
1946   }
1947
1948   foreach my $svc_phone ( @svc_phone ) {
1949     my @cols = map { $svc_phone->$_ } @fields;
1950     if($p->{'format'} eq 'csv') {
1951         return { 'error' => 'Unable to create CSV' } 
1952             unless $csv->combine(@cols);
1953         $content .= $csv->string;
1954     }
1955     elsif($p->{'format'} eq 'xls') {
1956         $xls_c = 0;
1957         foreach ( @cols ) {
1958             $xls->write($xls_r,$xls_c++,$_);
1959         }
1960         $xls_r++;
1961     }
1962   }
1963
1964   $xls_workbook->close() if $p->{'format'} eq 'xls';
1965   
1966   { content => $content, format => $p->{'format'}, };
1967 }
1968
1969 sub get_ticket {
1970   my $p = shift;
1971   my($context, $session, $custnum) = _custoragent_session_custnum($p);
1972   return { 'error' => $session } if $context eq 'error';
1973
1974   warn "$me get_ticket: initializing ticket system\n" if $DEBUG;
1975   FS::TicketSystem->init();
1976
1977   if(length($p->{'reply'})) {
1978 # currently this allows anyone to correspond on any ticket as fs_selfservice
1979 # probably bad...
1980       my @err_or_res = FS::TicketSystem->correspond_ticket(
1981         '', #create RT session based on FS CurrentUser (fs_selfservice)
1982         'ticket_id' => $p->{'ticket_id'},
1983         'content' => $p->{'reply'},
1984       );
1985     
1986     return { 'error' => 'unable to reply to ticket' } 
1987         unless ( $err_or_res[0] != 0 && defined $err_or_res[2] );
1988   }
1989
1990   warn "$me get_ticket: getting ticket\n" if $DEBUG;
1991   my $err_or_ticket = FS::TicketSystem->get_ticket(
1992     '', #create RT session based on FS CurrentUser (fs_selfservice)
1993     'ticket_id' => $p->{'ticket_id'},
1994   );
1995
1996   if ( ref($err_or_ticket) ) {
1997
1998 # since we're bypassing the RT security/permissions model by always using
1999 # fs_selfservice as the RT user (as opposed to a requestor, which we
2000 # can't do since we want all tickets linked to a cust), we check below whether
2001 # the requested ticket was actually linked to this customer
2002     my @custs = @{$err_or_ticket->{'custs'}};
2003     my @txns = @{$err_or_ticket->{'txns'}};
2004     my @filtered_txns;
2005
2006     return { 'error' => 'no customer' } unless ( $custnum && scalar(@custs) );
2007
2008     return { 'error' => 'invalid ticket requested' } 
2009         unless grep($_ eq $custnum, @custs);
2010
2011     foreach my $txn ( @txns ) {
2012         push @filtered_txns, $txn 
2013             if ($txn->{'type'} eq 'EmailRecord' 
2014                 || $txn->{'type'} eq 'Correspond'
2015                 || $txn->{'type'} eq 'Create');
2016     }
2017
2018     warn "$me get_ticket: sucessful: \n"
2019       if $DEBUG;
2020     return { 'error'     => '',
2021              'transactions' => \@filtered_txns,
2022              'ticket_id' => $p->{'ticket_id'},
2023            };
2024   } else {
2025     warn "$me create_ticket: unsucessful: $err_or_ticket\n"
2026       if $DEBUG;
2027     return { 'error' => $err_or_ticket };
2028   }
2029 }
2030
2031
2032 #--
2033
2034 sub _custoragent_session_custnum {
2035   my $p = shift;
2036
2037   my($context, $session, $custnum);
2038   if ( $p->{'session_id'} ) {
2039
2040     $context = 'customer';
2041     $session = _cache->get($p->{'session_id'})
2042       or return ( 'error' => "Can't resume session" ); #better error message
2043     $custnum = $session->{'custnum'};
2044
2045   } elsif ( $p->{'agent_session_id'} ) {
2046
2047     $context = 'agent';
2048     my $agent_cache = new FS::ClientAPI_SessionCache( {
2049       'namespace' => 'FS::ClientAPI::Agent',
2050     } );
2051     $session = $agent_cache->get($p->{'agent_session_id'})
2052       or return ( 'error' => "Can't resume session" ); #better error message
2053     $custnum = $p->{'custnum'};
2054
2055   } else {
2056     $context = 'error';
2057     return ( 'error' => "Can't resume session" ); #better error message
2058   }
2059
2060   ($context, $session, $custnum);
2061
2062 }
2063
2064 1;
2065