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