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