add two-step payment processing to self-service, 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 ( defined($p->{'agentnum'}) and $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 date_format ) ),
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', $cust_main->agentnum);
298
299   $info->{'edit_ticket_subject'} =
300       $conf->exists('ticket_system-selfservice_edit_subject') && 
301       $cust_main->edit_subject;
302
303   return { %$info,
304            'custnum'       => $custnum,
305            'access_pkgnum' => $session->{'pkgnum'},
306            'access_svcnum' => $session->{'svcnum'},
307          };
308 }
309
310 sub customer_info {
311   my $p = shift;
312
313   my($context, $session, $custnum) = _custoragent_session_custnum($p);
314   return { 'error' => $session } if $context eq 'error';
315
316   my %return;
317
318   my $conf = new FS::Conf;
319   if ($conf->exists('cust_main-require_address2')) {
320     $return{'require_address2'} = '1';
321   }else{
322     $return{'require_address2'} = '';
323   }
324
325   if ( $FS::TicketSystem::system ) {
326     warn "$me customer_info: initializing ticket system\n" if $DEBUG;
327     FS::TicketSystem->init();
328   }
329  
330   if ( $custnum ) { #customer record
331
332     my $search = { 'custnum' => $custnum };
333     $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
334     my $cust_main = qsearchs('cust_main', $search )
335       or return { 'error' => "unknown custnum $custnum" };
336
337     if ( $session->{'pkgnum'} ) { 
338       $return{balance} = $cust_main->balance_pkgnum( $session->{'pkgnum'} );
339     } else {
340       $return{balance} = $cust_main->balance;
341     }
342
343     my @tickets = $cust_main->tickets;
344     # unavoidable false laziness w/ httemplate/view/cust_main/tickets.html
345     if ( FS::TicketSystem->selfservice_priority ) {
346       my $dir = $conf->exists('ticket_system-priority_reverse') ? -1 : 1;
347       $return{tickets} = [ 
348         sort { 
349           (
350             ($a->{'_selfservice_priority'} eq '') <=>
351             ($b->{'_selfservice_priority'} eq '')
352           ) ||
353           ( $dir * 
354             ($b->{'_selfservice_priority'} <=> $a->{'_selfservice_priority'}) 
355           )
356         } @tickets
357       ];
358     }
359     else {
360       $return{tickets} = \@tickets;
361     }
362
363     unless ( $session->{'pkgnum'} ) {
364       my @open = map {
365                        {
366                          invnum => $_->invnum,
367                          date   => time2str("%b %o, %Y", $_->_date),
368                          owed   => $_->owed,
369                        };
370                      } $cust_main->open_cust_bill;
371       $return{open_invoices} = \@open;
372     }
373
374     $return{small_custview} =
375       small_custview( $cust_main,
376                       scalar($conf->config('countrydefault')),
377                       ( $session->{'pkgnum'} ? 1 : 0 ), #nobalance
378                     );
379
380     $return{name} = $cust_main->first. ' '. $cust_main->get('last');
381
382     for (@cust_main_editable_fields) {
383       $return{$_} = $cust_main->get($_);
384     }
385
386     if ( $cust_main->payby =~ /^(CARD|DCRD)$/ ) {
387       $return{payinfo} = $cust_main->paymask;
388       @return{'month', 'year'} = $cust_main->paydate_monthyear;
389     }
390
391     $return{'invoicing_list'} =
392       join(', ', grep { $_ !~ /^(POST|FAX)$/ } $cust_main->invoicing_list );
393     $return{'postal_invoicing'} =
394       0 < ( grep { $_ eq 'POST' } $cust_main->invoicing_list );
395
396     if (scalar($conf->config('support_packages'))) {
397       my @support_services = ();
398       foreach ($cust_main->support_services) {
399         my $seconds = $_->svc_x->seconds;
400         my $time_remaining = (($seconds < 0) ? '-' : '' ).
401                              int(abs($seconds)/3600)."h".
402                              sprintf("%02d",(abs($seconds)%3600)/60)."m";
403         my $cust_pkg = $_->cust_pkg;
404         my $pkgnum = '';
405         my $pkg = '';
406         $pkgnum = $cust_pkg->pkgnum if $cust_pkg;
407         $pkg = $cust_pkg->part_pkg->pkg if $cust_pkg;
408         push @support_services, { svcnum => $_->svcnum,
409                                   time => $time_remaining,
410                                   pkgnum => $pkgnum,
411                                   pkg => $pkg,
412                                 };
413       }
414       $return{support_services} = \@support_services;
415     }
416
417     if ( $conf->config('prepayment_discounts-credit_type') ) {
418       #need to eval?
419       $return{discount_terms_hash} = { $cust_main->discount_terms_hash };
420     }
421
422     if ( $session->{'svcnum'} ) {
423       my $cust_svc = qsearchs('cust_svc', { 'svcnum' => $session->{'svcnum'} });
424       $return{'svc_label'} = ($cust_svc->label)[1] if $cust_svc;
425     }
426
427   } elsif ( $session->{'svcnum'} ) { #no customer record
428
429     my $svc_acct = qsearchs('svc_acct', { 'svcnum' => $session->{'svcnum'} } )
430       or die "unknown svcnum";
431     $return{name} = $svc_acct->email;
432
433   } else {
434
435     return { 'error' => 'Expired session' }; #XXX redirect to login w/this err!
436
437   }
438
439   return { 'error'          => '',
440            'custnum'        => $custnum,
441            %return,
442          };
443
444 }
445
446 sub edit_info {
447   my $p = shift;
448   my $session = _cache->get($p->{'session_id'})
449     or return { 'error' => "Can't resume session" }; #better error message
450
451   my $custnum = $session->{'custnum'}
452     or return { 'error' => "no customer record" };
453
454   my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
455     or return { 'error' => "unknown custnum $custnum" };
456
457   my $new = new FS::cust_main { $cust_main->hash };
458   $new->set( $_ => $p->{$_} )
459     foreach grep { exists $p->{$_} } @cust_main_editable_fields;
460
461   my $payby = '';
462   if (exists($p->{'payby'})) {
463     $p->{'payby'} =~ /^([A-Z]{4})$/
464       or return { 'error' => "illegal_payby " . $p->{'payby'} };
465     $payby = $1;
466   }
467
468   if ( $payby =~ /^(CARD|DCRD)$/ ) {
469
470     $new->paydate($p->{'year'}. '-'. $p->{'month'}. '-01');
471
472     if ( $new->payinfo eq $cust_main->paymask ) {
473       $new->payinfo($cust_main->payinfo);
474     } else {
475       $new->payinfo($p->{'payinfo'});
476     }
477
478     $new->set( 'payby' => $p->{'auto'} ? 'CARD' : 'DCRD' );
479
480   } elsif ( $payby =~ /^(CHEK|DCHK)$/ ) {
481
482     my $payinfo;
483     $p->{'payinfo1'} =~ /^([\dx]+)$/
484       or return { 'error' => "illegal account number ". $p->{'payinfo1'} };
485     my $payinfo1 = $1;
486      $p->{'payinfo2'} =~ /^([\dx]+)$/
487       or return { 'error' => "illegal ABA/routing number ". $p->{'payinfo2'} };
488     my $payinfo2 = $1;
489     $payinfo = $payinfo1. '@'. $payinfo2;
490
491     $new->payinfo( ($payinfo eq $cust_main->paymask)
492                      ? $cust_main->payinfo
493                      : $payinfo
494                  );
495
496     $new->set( 'payby' => $p->{'auto'} ? 'CHEK' : 'DCHK' );
497
498   } elsif ( $payby =~ /^(BILL)$/ ) {
499     #no-op
500   } elsif ( $payby ) {  #notyet ready
501     return { 'error' => "unknown payby $payby" };
502   }
503
504   my @invoicing_list;
505   if ( exists $p->{'invoicing_list'} || exists $p->{'postal_invoicing'} ) {
506     #false laziness with httemplate/edit/process/cust_main.cgi
507     @invoicing_list = split( /\s*\,\s*/, $p->{'invoicing_list'} );
508     push @invoicing_list, 'POST' if $p->{'postal_invoicing'};
509   } else {
510     @invoicing_list = $cust_main->invoicing_list;
511   }
512
513   my $error = $new->replace($cust_main, \@invoicing_list);
514   return { 'error' => $error } if $error;
515   #$cust_main = $new;
516   
517   return { 'error' => '' };
518 }
519
520 sub payment_info {
521   my $p = shift;
522   my $session = _cache->get($p->{'session_id'})
523     or return { 'error' => "Can't resume session" }; #better error message
524
525   ##
526   #generic
527   ##
528
529   my $conf = new FS::Conf;
530   use vars qw($payment_info); #cache for performance
531   unless ( $payment_info ) {
532
533     my %states = map { $_->state => 1 }
534                    qsearch('cust_main_county', {
535                      'country' => $conf->config('countrydefault') || 'US'
536                    } );
537
538     my %cust_paybys = map { $_ => 1 }
539                       map { FS::payby->payby2payment($_) }
540                           $conf->config('signup_server-payby');
541
542     my @cust_paybys = keys %cust_paybys;
543
544     $payment_info = {
545
546       #list all counties/states/countries
547       'cust_main_county' => 
548         [ map { $_->hashref } qsearch('cust_main_county', {}) ],
549
550       #shortcut for one-country folks
551       'states' =>
552         [ sort { $a cmp $b } keys %states ],
553
554       'card_types' => card_types(),
555
556       'paytypes' => [ @FS::cust_main::paytypes ],
557
558       'paybys' => [ $conf->config('signup_server-payby') ],
559       'cust_paybys' => \@cust_paybys,
560
561       'stateid_label' => FS::Msgcat::_gettext('stateid'),
562       'stateid_state_label' => FS::Msgcat::_gettext('stateid_state'),
563
564       'show_ss'  => $conf->exists('show_ss'),
565       'show_stateid' => $conf->exists('show_stateid'),
566       'show_paystate' => $conf->exists('show_bankstate'),
567
568       'save_unchecked' => $conf->exists('selfservice-save_unchecked'),
569
570       'credit_card_surcharge_percentage' => $conf->config('credit-card-surcharge-percentage'),
571     };
572
573   }
574
575   ##
576   #customer-specific
577   ##
578
579   my %return = %$payment_info;
580
581   my $custnum = $session->{'custnum'};
582
583   my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
584     or return { 'error' => "unknown custnum $custnum" };
585
586   $return{'hide_payment_fields'} = [
587     map { 
588       my $pg = payment_gateway($cust_main, $_);
589       $pg && $pg->gateway_namespace eq 'Business::OnlineThirdPartyPayment';
590     } @{ $return{cust_paybys} }
591   ];
592
593   $return{balance} = $cust_main->balance; #XXX pkg-balances?
594
595   $return{payname} = $cust_main->payname
596                      || ( $cust_main->first. ' '. $cust_main->get('last') );
597
598   $return{$_} = $cust_main->get($_) for qw(address1 address2 city state zip);
599
600   $return{payby} = $cust_main->payby;
601   $return{stateid_state} = $cust_main->stateid_state;
602
603   if ( $cust_main->payby =~ /^(CARD|DCRD)$/ ) {
604     $return{card_type} = cardtype($cust_main->payinfo);
605     $return{payinfo} = $cust_main->paymask;
606
607     @return{'month', 'year'} = $cust_main->paydate_monthyear;
608
609   }
610
611   if ( $cust_main->payby =~ /^(CHEK|DCHK)$/ ) {
612     my ($payinfo1, $payinfo2) = split '@', $cust_main->paymask;
613     $return{payinfo1} = $payinfo1;
614     $return{payinfo2} = $payinfo2;
615     $return{paytype}  = $cust_main->paytype;
616     $return{paystate} = $cust_main->paystate;
617
618   }
619
620   if ( $conf->config('prepayment_discounts-credit_type') ) {
621     #need to eval?
622     $return{discount_terms_hash} = { $cust_main->discount_terms_hash };
623   }
624
625   #doubleclick protection
626   my $_date = time;
627   $return{paybatch} = "webui-MyAccount-$_date-$$-". rand() * 2**32;
628
629   return { 'error' => '',
630            %return,
631          };
632
633 }
634
635 #some false laziness with httemplate/process/payment.cgi - look there for
636 #ACH and CVV support stuff
637
638 sub validate_payment {
639   my $p = shift;
640
641   my $session = _cache->get($p->{'session_id'})
642     or return { 'error' => "Can't resume session" }; #better error message
643
644   my $custnum = $session->{'custnum'};
645
646   my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
647     or return { 'error' => "unknown custnum $custnum" };
648
649   $p->{'amount'} =~ /^\s*(\d+(\.\d{2})?)\s*$/
650     or return { 'error' => gettext('illegal_amount') };
651   my $amount = $1;
652   return { error => 'Amount must be greater than 0' } unless $amount > 0;
653
654   $p->{'discount_term'} =~ /^\s*(\d*)\s*$/
655     or return { 'error' => gettext('illegal_discount_term'). ': '. $p->{'discount_term'} };
656   my $discount_term = $1;
657
658   $p->{'payname'} =~ /^([\w \,\.\-\']+)$/
659     or return { 'error' => gettext('illegal_name'). " payname: ". $p->{'payname'} };
660   my $payname = $1;
661
662   $p->{'paybatch'} =~ /^([\w \!\@\#\$\%\&\(\)\-\+\;\:\'\"\,\.\?\/\=]*)$/
663     or return { 'error' => gettext('illegal_text'). " paybatch: ". $p->{'paybatch'} };
664   my $paybatch = $1;
665
666   $p->{'payby'} ||= 'CARD';
667   $p->{'payby'} =~ /^([A-Z]{4})$/
668     or return { 'error' => "illegal_payby " . $p->{'payby'} };
669   my $payby = $1;
670
671   #false laziness w/process/payment.cgi
672   my $payinfo;
673   my $paycvv = '';
674   if ( $payby eq 'CHEK' || $payby eq 'DCHK' ) {
675   
676     $p->{'payinfo1'} =~ /^([\dx]+)$/
677       or return { 'error' => "illegal account number ". $p->{'payinfo1'} };
678     my $payinfo1 = $1;
679      $p->{'payinfo2'} =~ /^([\dx]+)$/
680       or return { 'error' => "illegal ABA/routing number ". $p->{'payinfo2'} };
681     my $payinfo2 = $1;
682     $payinfo = $payinfo1. '@'. $payinfo2;
683
684     $payinfo = $cust_main->payinfo
685       if $cust_main->paymask eq $payinfo;
686    
687   } elsif ( $payby eq 'CARD' || $payby eq 'DCRD' ) {
688    
689     $payinfo = $p->{'payinfo'};
690
691     #more intelligent mathing will be needed here if you change
692     #card_masking_method and don't remove existing paymasks
693     $payinfo = $cust_main->payinfo
694       if $cust_main->paymask eq $payinfo;
695
696     $payinfo =~ s/\D//g;
697     $payinfo =~ /^(\d{13,16}|\d{8,9})$/
698       or return { 'error' => gettext('invalid_card') }; # . ": ". $self->payinfo
699     $payinfo = $1;
700
701     validate($payinfo)
702       or return { 'error' => gettext('invalid_card') }; # . ": ". $self->payinfo
703     return { 'error' => gettext('unknown_card_type') }
704       if $payinfo !~ /^99\d{14}$/ && cardtype($payinfo) eq "Unknown";
705
706     if ( length($p->{'paycvv'}) && $p->{'paycvv'} !~ /^\s*$/ ) {
707       if ( cardtype($payinfo) eq 'American Express card' ) {
708         $p->{'paycvv'} =~ /^\s*(\d{4})\s*$/
709           or return { 'error' => "CVV2 (CID) for American Express cards is four digits." };
710         $paycvv = $1;
711       } else {
712         $p->{'paycvv'} =~ /^\s*(\d{3})\s*$/
713           or return { 'error' => "CVV2 (CVC2/CID) is three digits." };
714         $paycvv = $1;
715       }
716     }
717   
718   } else {
719     die "unknown payby $payby";
720   }
721
722   my %payby2fields = (
723     'CARD' => [ qw( paystart_month paystart_year payissue payip
724                     address1 address2 city state zip country    ) ],
725     'CHEK' => [ qw( ss paytype paystate stateid stateid_state payip ) ],
726   );
727
728   my $card_type = '';
729   $card_type = cardtype($payinfo) if $payby eq 'CARD';
730
731   { 
732     'cust_main'      => $cust_main, #XXX or just custnum??
733     'amount'         => $amount,
734     'payby'          => $payby,
735     'payinfo'        => $payinfo,
736     'paymask'        => $cust_main->mask_payinfo( $payby, $payinfo ),
737     'card_type'      => $card_type,
738     'paydate'        => $p->{'year'}. '-'. $p->{'month'}. '-01',
739     'paydate_pretty' => $p->{'month'}. ' / '. $p->{'year'},
740     'payname'        => $payname,
741     'paybatch'       => $paybatch, #this doesn't actually do anything
742     'paycvv'         => $paycvv,
743     'payname'        => $payname,
744     'discount_term'  => $discount_term,
745     'pkgnum'         => $session->{'pkgnum'},
746     map { $_ => $p->{$_} } ( @{ $payby2fields{$payby} },
747                              qw( save auto ),
748                            )
749   };
750
751 }
752
753 sub store_payment {
754   my $p = shift;
755
756   my $validate = validate_payment($p);
757   return $validate if $validate->{'error'};
758
759   my $conf = new FS::Conf;
760   my $timeout = $conf->config('selfservice-session_timeout') || '1 hour'; #?
761   _cache->set( 'payment_'.$p->{'session_id'}, $validate, $timeout );
762
763   +{ map { $_=>$validate->{$_} }
764       qw( card_type paymask payname paydate_pretty amount )
765   };
766
767 }
768
769 sub process_stored_payment {
770   my $p = shift;
771
772   my $session_id = $p->{'session_id'};
773
774   my $payment_info = _cache->get( "payment_$session_id" )
775     or return { 'error' => "Can't resume session" }; #better error message
776
777   do_process_payment($payment_info);
778
779 }
780
781 sub process_payment {
782   my $p = shift;
783
784   my $payment_info = validate_payment($p);
785   return $payment_info if $payment_info->{'error'};
786
787   do_process_payment($payment_info);
788
789 }
790
791 sub do_process_payment {
792   my $validate = shift;
793
794   my $cust_main = $validate->{'cust_main'};
795
796   my $amount = delete $validate->{'amount'};
797   my $paynum = '';
798
799   my $payby = delete $validate->{'payby'};
800
801   my $error = $cust_main->realtime_bop( $FS::payby::payby2bop{$payby}, $amount,
802     'quiet'       => 1,
803     'selfservice' => 1,
804     'fake'        => 1, #XXX DO NOT CHECK ME IN
805     'paynum_ref'  => \$paynum,
806     %$validate,
807   );
808   return { 'error' => $error } if $error;
809
810   $cust_main->apply_payments;
811
812   if ( $validate->{'save'} ) {
813     my $new = new FS::cust_main { $cust_main->hash };
814     if ($validate->{'payby'} eq 'CARD' || $validate->{'payby'} eq 'DCRD') {
815       $new->set( $_ => $validate->{$_} )
816         foreach qw( payname paystart_month paystart_year payissue payip
817                     address1 address2 city state zip country );
818       $new->set( 'payby' => $validate->{'auto'} ? 'CARD' : 'DCRD' );
819     } elsif ($payby eq 'CHEK' || $payby eq 'DCHK') {
820       $new->set( $_ => $validate->{$_} )
821         foreach qw( payname payip paytype paystate
822                     stateid stateid_state );
823       $new->set( 'payby' => $validate->{'auto'} ? 'CHEK' : 'DCHK' );
824     }
825     $new->set( 'payinfo' => $cust_main->card_token || $validate->{'payinfo'} );
826     $new->set( 'paydate' => $validate->{'paydate'} );
827     my $error = $new->replace($cust_main);
828     if ( $error ) {
829       #no, this causes customers to process their payments again
830       #return { 'error' => $error };
831       #XXX just warn verosely for now so i can figure out how these happen in
832       # the first place, eventually should redirect them to the "change
833       #address" page but indicate the payment did process??
834       delete($validate->{'payinfo'}); #don't want to log this!
835       warn "WARNING: error changing customer info when processing payment (not returning to customer as a processing error): $error\n".
836            "NEW: ". Dumper($new)."\n".
837            "OLD: ". Dumper($cust_main)."\n".
838            "PACKET: ". Dumper($validate)."\n";
839     #} else {
840       #not needed...
841       #$cust_main = $new;
842     }
843   }
844
845   my $cust_pay = '';
846   my $receipt_html = '';
847   if ($paynum) {
848       # currently supported for realtime CC only; send receipt data to SS
849       $cust_pay = qsearchs('cust_pay', { 'paynum' => $paynum } );
850       if($cust_pay) {
851         $receipt_html = qq!
852 <TABLE BGCOLOR="#cccccc" BORDER=0 CELLSPACING=2>
853
854 <TR>
855   <TD ALIGN="right">Payment#</TD>
856   <TD BGCOLOR="#FFFFFF"><B>! . $cust_pay->paynum . qq!</B></TD>
857 </TR>
858
859 <TR>
860   <TD ALIGN="right">Date</TD>
861
862   <TD BGCOLOR="#FFFFFF"><B>! . 
863         time2str("%a&nbsp;%b&nbsp;%o,&nbsp;%Y&nbsp;%r", $cust_pay->_date)
864                                                             . qq!</B></TD>
865 </TR>
866
867
868 <TR>
869   <TD ALIGN="right">Amount</TD>
870   <TD BGCOLOR="#FFFFFF"><B>! . sprintf('%.2f', $cust_pay->paid) . qq!</B></TD>
871
872 </TR>
873
874 <TR>
875   <TD ALIGN="right">Payment method</TD>
876   <TD BGCOLOR="#FFFFFF"><B>! . $cust_pay->payby_name .' #'. $cust_pay->paymask
877                                                                 . qq!</B></TD>
878 </TR>
879
880 </TABLE>
881 !;
882       }
883   }
884
885   if ( $cust_pay ) {
886
887     my($gw, $auth, $order) = split(':', $cust_pay->paybatch);
888
889     return {
890       'error'        => '',
891       'amount'       => sprintf('%.2f', $cust_pay->paid),
892       'date'         => $cust_pay->_date,
893       'date_pretty'  => time2str('%Y-%m-%d', $cust_pay->_date),
894       'time_pretty'  => time2str('%T', $cust_pay->_date),
895       'auth_num'     => $auth,
896       'order_num'    => $order,
897       'receipt_html' => $receipt_html,
898     };
899
900   } else {
901
902     return {
903       'error'        => '',
904       'receipt_html' => '',
905     };
906
907   }
908
909 }
910
911 sub realtime_collect {
912   my $p = shift;
913
914   my $session = _cache->get($p->{'session_id'})
915     or return { 'error' => "Can't resume session" }; #better error message
916
917   my $custnum = $session->{'custnum'};
918
919   my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
920     or return { 'error' => "unknown custnum $custnum" };
921
922   my $amount;
923   if ( $p->{'amount'} ) {
924     $amount = $p->{'amount'};
925   }
926   elsif ( $session->{'pkgnum'} ) {
927     $amount = $cust_main->balance_pkgnum( $session->{'pkgnum'} );
928   }
929   else {
930     $amount = $cust_main->balance;
931   }
932
933   my $error = $cust_main->realtime_collect(
934     'method'     => $p->{'method'},
935     'amount'     => $amount,
936     'pkgnum'     => $session->{'pkgnum'},
937     'session_id' => $p->{'session_id'},
938     'apply'      => 1,
939     'selfservice'=> 1,
940   );
941   return { 'error' => $error } unless ref( $error );
942
943   return { 'error' => '', amount => $amount, %$error };
944 }
945
946 sub process_payment_order_pkg {
947   my $p = shift;
948
949   my $hr = process_payment($p);
950   return $hr if $hr->{'error'};
951
952   order_pkg($p);
953 }
954
955 sub process_payment_order_renew {
956   my $p = shift;
957
958   my $hr = process_payment($p);
959   return $hr if $hr->{'error'};
960
961   order_renew($p);
962 }
963
964 sub process_prepay {
965
966   my $p = shift;
967
968   my $session = _cache->get($p->{'session_id'})
969     or return { 'error' => "Can't resume session" }; #better error message
970
971   my %return;
972
973   my $custnum = $session->{'custnum'};
974
975   my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
976     or return { 'error' => "unknown custnum $custnum" };
977
978   my( $amount, $seconds, $upbytes, $downbytes, $totalbytes ) = ( 0, 0, 0, 0, 0 );
979   my $error = $cust_main->recharge_prepay( $p->{'prepaid_cardnum'},
980                                            \$amount,
981                                            \$seconds,
982                                            \$upbytes,
983                                            \$downbytes,
984                                            \$totalbytes,
985                                          );
986
987   return { 'error' => $error } if $error;
988
989   return { 'error'     => '',
990            'amount'    => $amount,
991            'seconds'   => $seconds,
992            'duration'  => duration_exact($seconds),
993            'upbytes'   => $upbytes,
994            'upload'    => FS::UI::bytecount::bytecount_unexact($upbytes),
995            'downbytes' => $downbytes,
996            'download'  => FS::UI::bytecount::bytecount_unexact($downbytes),
997            'totalbytes'=> $totalbytes,
998            'totalload' => FS::UI::bytecount::bytecount_unexact($totalbytes),
999          };
1000
1001 }
1002
1003 sub invoice {
1004   my $p = shift;
1005   my $session = _cache->get($p->{'session_id'})
1006     or return { 'error' => "Can't resume session" }; #better error message
1007
1008   my $custnum = $session->{'custnum'};
1009
1010   my $invnum = $p->{'invnum'};
1011
1012   my $cust_bill = qsearchs('cust_bill', { 'invnum'  => $invnum,
1013                                           'custnum' => $custnum } )
1014     or return { 'error' => "Can't find invnum" };
1015
1016   #my %return;
1017
1018   return { 'error'        => '',
1019            'invnum'       => $invnum,
1020            'invoice_text' => join('', $cust_bill->print_text ),
1021            'invoice_html' => $cust_bill->print_html( { unsquelch_cdr => 1 } ),
1022          };
1023
1024 }
1025
1026 sub invoice_pdf {
1027   my $p = shift;
1028   my $session = _cache->get($p->{'session_id'})
1029     or return { 'error' => "Can't resume session" }; #better error message
1030
1031   my $custnum = $session->{'custnum'};
1032
1033   my $invnum = $p->{'invnum'};
1034
1035   my $cust_bill = qsearchs('cust_bill', { 'invnum'  => $invnum,
1036                                           'custnum' => $custnum } )
1037     or return { 'error' => "Can't find invnum" };
1038
1039   #my %return;
1040
1041   return { 'error'       => '',
1042            'invnum'      => $invnum,
1043            'invoice_pdf' => $cust_bill->print_pdf( { unsquelch_cdr => 1 } ),
1044          };
1045
1046 }
1047
1048 sub invoice_logo {
1049   my $p = shift;
1050
1051   #sessioning for this?  how do we get the session id to the backend invoice
1052   # template so it can add it to the link, blah
1053
1054   my $agentnum = '';
1055   if ( $p->{'invnum'} ) {
1056     my $cust_bill = qsearchs('cust_bill', { 'invnum' => $p->{'invnum'} } )
1057       or return { 'error' => 'unknown invnum' };
1058     $agentnum = $cust_bill->cust_main->agentnum;
1059   }
1060
1061   my $templatename = $p->{'template'} || $p->{'templatename'};
1062
1063   #false laziness-ish w/view/cust_bill-logo.cgi
1064
1065   my $conf = new FS::Conf;
1066   if ( $templatename =~ /^([^\.\/]*)$/ && $conf->exists("logo_$1.png") ) {
1067     $templatename = "_$1";
1068   } else {
1069     $templatename = '';
1070   }
1071
1072   my $filename = "logo$templatename.png";
1073
1074   return { 'error'        => '',
1075            'logo'         => $conf->config_binary($filename, $agentnum),
1076            'content_type' => 'image/png', #should allow gif, jpg too
1077          };
1078 }
1079
1080
1081 sub list_invoices {
1082   my $p = shift;
1083   my $session = _cache->get($p->{'session_id'})
1084     or return { 'error' => "Can't resume session" }; #better error message
1085
1086   my $custnum = $session->{'custnum'};
1087
1088   my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1089     or return { 'error' => "unknown custnum $custnum" };
1090
1091   my @cust_bill = $cust_main->cust_bill;
1092
1093   my $balance = 0;
1094
1095   return  { 'error'       => '',
1096             'balance'     => $cust_main->balance,
1097             'invoices'    => [
1098               map {
1099                     my $owed = $_->owed;
1100                     $balance += $owed;
1101                     +{ 'invnum'     => $_->invnum,
1102                        '_date'      => $_->_date,
1103                        'date'       => time2str("%b %o, %Y", $_->_date),
1104                        'date_short' => time2str("%m-%d-%Y",  $_->_date),
1105                        'previous'   => sprintf('%.2f', ($_->previous)[0]),
1106                        'charged'    => sprintf('%.2f', $_->charged),
1107                        'owed'       => sprintf('%.2f', $owed),
1108                        'balance'    => sprintf('%.2f', $balance),
1109                      }
1110                   }
1111                   @cust_bill
1112             ]
1113           };
1114 }
1115
1116 sub cancel {
1117   my $p = shift;
1118   my $session = _cache->get($p->{'session_id'})
1119     or return { 'error' => "Can't resume session" }; #better error message
1120
1121   my $custnum = $session->{'custnum'};
1122
1123   my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1124     or return { 'error' => "unknown custnum $custnum" };
1125
1126   my @errors = $cust_main->cancel( 'quiet'=>1 );
1127
1128   my $error = scalar(@errors) ? join(' / ', @errors) : '';
1129
1130   return { 'error' => $error };
1131
1132 }
1133
1134 sub list_pkgs {
1135   my $p = shift;
1136
1137   my($context, $session, $custnum) = _custoragent_session_custnum($p);
1138   return { 'error' => $session } if $context eq 'error';
1139
1140   my $search = { 'custnum' => $custnum };
1141   $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
1142   my $cust_main = qsearchs('cust_main', $search )
1143     or return { 'error' => "unknown custnum $custnum" };
1144
1145   my $conf = new FS::Conf;
1146   
1147 # the duplication below is necessary:
1148 # 1. to maintain the current buggy behaviour wrt the cust_pkg and part_pkg
1149 # hashes overwriting each other (setup and no_auto fields). Fixing that is a
1150 # non-backwards-compatible change breaking the software of anyone using the API
1151 # instead of the stock selfservice
1152 # 2. to return cancelled packages as well - for wholesale and non-wholesale
1153   if( $conf->exists('selfservice_server-view-wholesale') ) {
1154     return { 'svcnum'   => $session->{'svcnum'},
1155             'custnum'  => $custnum,
1156             'cust_pkg' => [ map {
1157                           { $_->hash,
1158                             part_pkg => [ map $_->hashref, $_->part_pkg ],
1159                             part_svc =>
1160                               [ map $_->hashref, $_->available_part_svc ],
1161                             cust_svc => 
1162                               [ map { my $ref = { $_->hash,
1163                                                   label => [ $_->label ],
1164                                                 };
1165                                       $ref->{_password} = $_->svc_x->_password
1166                                         if $context eq 'agent'
1167                                         && $conf->exists('agent-showpasswords')
1168                                         && $_->part_svc->svcdb eq 'svc_acct';
1169                                       $ref;
1170                                     } $_->cust_svc
1171                               ],
1172                           };
1173                         } $cust_main->cust_pkg
1174                   ],
1175     'small_custview' =>
1176       small_custview( $cust_main, $conf->config('countrydefault') ),
1177     'wholesale_view' => 1,
1178     'login_svcpart' => [ $conf->config('selfservice_server-login_svcpart') ],
1179     'date_format' => $conf->config('date_format') || '%m/%d/%Y',
1180     'lnp' => $conf->exists('svc_phone-lnp'),
1181       };
1182   }
1183
1184   { 'svcnum'   => $session->{'svcnum'},
1185     'custnum'  => $custnum,
1186     'cust_pkg' => [ map {
1187                           my $primary_cust_svc = $_->primary_cust_svc;
1188                           +{ $_->hash,
1189                             $_->part_pkg->hash,
1190                             status => $_->status,
1191                             part_svc =>
1192                               [ map $_->hashref, $_->available_part_svc ],
1193                             cust_svc => 
1194                               [ map { my $ref = { $_->hash,
1195                                                   label => [ $_->label ],
1196                                                 };
1197                                       $ref->{_password} = $_->svc_x->_password
1198                                         if $context eq 'agent'
1199                                         && $conf->exists('agent-showpasswords')
1200                                         && $_->part_svc->svcdb eq 'svc_acct';
1201                                       $ref->{svchash} = { $_->svc_x->hash } if 
1202                                         $_->part_svc->svcdb eq 'svc_phone';
1203                                       $ref->{svchash}->{svcpart} =  $_->part_svc->svcpart
1204                                         if $_->part_svc->svcdb eq 'svc_phone'; # hack
1205                                       $ref;
1206                                     } $_->cust_svc
1207                               ],
1208                             primary_cust_svc =>
1209                               $primary_cust_svc
1210                                 ? { $primary_cust_svc->hash,
1211                                     label => [ $primary_cust_svc->label ],
1212                                     finger => $primary_cust_svc->svc_x->finger, #uuh
1213                                     $primary_cust_svc->part_svc->hash,
1214                                   }
1215                                 : {}, #'' ?
1216                           };
1217                         } $cust_main->ncancelled_pkgs
1218                   ],
1219     'small_custview' =>
1220       small_custview( $cust_main, $conf->config('countrydefault') ),
1221   };
1222
1223 }
1224
1225 sub list_svcs {
1226   my $p = shift;
1227
1228   my($context, $session, $custnum) = _custoragent_session_custnum($p);
1229   return { 'error' => $session } if $context eq 'error';
1230
1231   my $search = { 'custnum' => $custnum };
1232   $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
1233   my $cust_main = qsearchs('cust_main', $search )
1234     or return { 'error' => "unknown custnum $custnum" };
1235
1236   my @cust_svc = ();
1237   #foreach my $cust_pkg ( $cust_main->ncancelled_pkgs ) {
1238   foreach my $cust_pkg ( $p->{'ncancelled'} 
1239                          ? $cust_main->ncancelled_pkgs
1240                          : $cust_main->unsuspended_pkgs ) {
1241     next if $session->{'pkgnum'} && $cust_pkg->pkgnum != $session->{'pkgnum'};
1242     push @cust_svc, @{[ $cust_pkg->cust_svc ]}; #@{[ ]} to force array context
1243   }
1244   if ( $p->{'svcdb'} ) {
1245     my $svcdb = ref($p->{'svcdb'}) eq 'HASH'
1246                   ? $p->{'svcdb'}
1247                   : ref($p->{'svcdb'}) eq 'ARRAY'
1248                     ? { map { $_=>1 } @{ $p->{'svcdb'} } }
1249                     : { $p->{'svcdb'} => 1 };
1250     @cust_svc = grep $svcdb->{ $_->part_svc->svcdb }, @cust_svc
1251   }
1252
1253   #@svc_x = sort { $a->domain cmp $b->domain || $a->username cmp $b->username }
1254   #              @svc_x;
1255
1256     my $conf = new FS::Conf;
1257
1258   { 
1259     'svcnum'   => $session->{'svcnum'},
1260     'custnum'  => $custnum,
1261     'date_format' => $conf->config('date_format') || '%m/%d/%Y',
1262     'view_usage_nodomain' => $conf->exists('selfservice-view_usage_nodomain'),
1263     'svcs'     => [
1264       map { 
1265             my $svc_x = $_->svc_x;
1266             my($label, $value) = $_->label;
1267             my $svcdb = $_->part_svc->svcdb;
1268             my $part_pkg = $_->cust_pkg->part_pkg;
1269
1270             my %hash = (
1271               'svcnum' => $_->svcnum,
1272               'svcdb'  => $svcdb,
1273               'label'  => $label,
1274               'value'  => $value,
1275             );
1276
1277             if ( $svcdb eq 'svc_acct' ) {
1278               %hash = (
1279                 %hash,
1280                 'username'   => $svc_x->username,
1281                 'email'      => $svc_x->email,
1282                 'seconds'    => $svc_x->seconds,
1283                 'upbytes'    => display_bytecount($svc_x->upbytes),
1284                 'downbytes'  => display_bytecount($svc_x->downbytes),
1285                 'totalbytes' => display_bytecount($svc_x->totalbytes),
1286
1287                 'recharge_amount'  => $part_pkg->option('recharge_amount',1),
1288                 'recharge_seconds' => $part_pkg->option('recharge_seconds',1),
1289                 'recharge_upbytes'    =>
1290                   display_bytecount($part_pkg->option('recharge_upbytes',1)),
1291                 'recharge_downbytes'  =>
1292                   display_bytecount($part_pkg->option('recharge_downbytes',1)),
1293                 'recharge_totalbytes' =>
1294                   display_bytecount($part_pkg->option('recharge_totalbytes',1)),
1295                 # more...
1296               );
1297
1298             } elsif ( $svcdb eq 'svc_phone' || $svcdb eq 'svc_port' ) {
1299               %hash = (
1300                 %hash,
1301               );
1302             }
1303
1304             \%hash;
1305           }
1306           @cust_svc
1307     ],
1308   };
1309
1310 }
1311
1312 sub port_graph {
1313   my $p = shift;
1314   _usage_details( \&_port_graph, $p,
1315                   'svcdb' => 'svc_port',
1316                 );
1317 }
1318
1319 sub _port_graph {
1320   my($svc_port, $begin, $end) = @_;
1321   my @usage = ();
1322   my $pngOrError = $svc_port->graph_png( start=>$begin, end=> $end );
1323   push @usage, { 'png' => $pngOrError };
1324   (@usage);
1325 }
1326
1327 sub _list_svc_usage {
1328   my($svc_acct, $begin, $end) = @_;
1329   my @usage = ();
1330   foreach my $part_export ( 
1331     map { qsearch ( 'part_export', { 'exporttype' => $_ } ) }
1332     qw( sqlradius sqlradius_withdomain )
1333   ) {
1334     push @usage, @ { $part_export->usage_sessions($begin, $end, $svc_acct) };
1335   }
1336   (@usage);
1337 }
1338
1339 sub list_svc_usage {
1340   _usage_details(\&_list_svc_usage, @_);
1341 }
1342
1343 sub _list_support_usage {
1344   my($svc_acct, $begin, $end) = @_;
1345   my @usage = ();
1346   foreach ( grep { $begin <= $_->_date && $_->_date <= $end }
1347             qsearch('acct_rt_transaction', { 'svcnum' => $svc_acct->svcnum })
1348           ) {
1349     push @usage, { 'seconds'  => $_->seconds,
1350                    'support'  => $_->support,
1351                    '_date'    => $_->_date,
1352                    'id'       => $_->transaction_id,
1353                    'creator'  => $_->creator,
1354                    'subject'  => $_->subject,
1355                    'status'   => $_->status,
1356                    'ticketid' => $_->ticketid,
1357                  };
1358   }
1359   (@usage);
1360 }
1361
1362 sub list_support_usage {
1363   _usage_details(\&_list_support_usage, @_);
1364 }
1365
1366 sub _list_cdr_usage {
1367   my($svc_phone, $begin, $end) = @_;
1368   map [ $_->downstream_csv('format' => 'default', 'keeparray' => 1) ], #XXX config for format
1369                        $svc_phone->get_cdrs( 'begin'=>$begin, 'end'=>$end, );
1370 }
1371
1372 sub list_cdr_usage {
1373   my $p = shift;
1374   _usage_details( \&_list_cdr_usage, $p,
1375                   'svcdb' => 'svc_phone',
1376                 );
1377 }
1378
1379 sub _usage_details {
1380   my($callback, $p, %opt) = @_;
1381
1382   my($context, $session, $custnum) = _custoragent_session_custnum($p);
1383   return { 'error' => $session } if $context eq 'error';
1384
1385   my $search = { 'svcnum' => $p->{'svcnum'} };
1386   $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
1387
1388   my $svcdb = $opt{'svcdb'} || 'svc_acct';
1389
1390   my $svc_x = qsearchs( $svcdb, $search );
1391   return { 'error' => 'No service selected in list_svc_usage' } 
1392     unless $svc_x;
1393
1394   my $header = $svcdb eq 'svc_phone'
1395                  ? [ split(',', FS::cdr::invoice_header('default') ) ]  #XXX
1396                  : [];
1397
1398   my $cust_pkg = $svc_x->cust_svc->cust_pkg;
1399   my $freq     = $cust_pkg->part_pkg->freq;
1400   my $start    = $cust_pkg->setup;
1401   #my $end      = $cust_pkg->bill; # or time?
1402   my $end      = time;
1403
1404   unless ( $p->{beginning} ) {
1405     $p->{beginning} = $cust_pkg->last_bill;
1406     $p->{ending}    = $end;
1407   }
1408
1409   my (@usage) = &$callback($svc_x, $p->{beginning}, $p->{ending});
1410
1411   #kinda false laziness with FS::cust_main::bill, but perhaps
1412   #we should really change this bit to DateTime and DateTime::Duration
1413   #
1414   #change this bit to use Date::Manip? CAREFUL with timezones (see
1415   # mailing list archive)
1416   my ($nsec,$nmin,$nhour,$nmday,$nmon,$nyear) =
1417     (localtime($p->{ending}) )[0,1,2,3,4,5];
1418   my ($psec,$pmin,$phour,$pmday,$pmon,$pyear) =
1419     (localtime($p->{beginning}) )[0,1,2,3,4,5];
1420
1421   if ( $freq =~ /^\d+$/ ) {
1422     $nmon += $freq;
1423     until ( $nmon < 12 ) { $nmon -= 12; $nyear++; }
1424     $pmon -= $freq;
1425     until ( $pmon >= 0 ) { $pmon += 12; $pyear--; }
1426   } elsif ( $freq =~ /^(\d+)w$/ ) {
1427     my $weeks = $1;
1428     $nmday += $weeks * 7;
1429     $pmday -= $weeks * 7;
1430   } elsif ( $freq =~ /^(\d+)d$/ ) {
1431     my $days = $1;
1432     $nmday += $days;
1433     $pmday -= $days;
1434   } elsif ( $freq =~ /^(\d+)h$/ ) {
1435     my $hours = $1;
1436     $nhour += $hours;
1437     $phour -= $hours;
1438   } else {
1439     return { 'error' => "unparsable frequency: ". $freq };
1440   }
1441   
1442   my $previous  = timelocal_nocheck($psec,$pmin,$phour,$pmday,$pmon,$pyear);
1443   my $next      = timelocal_nocheck($nsec,$nmin,$nhour,$nmday,$nmon,$nyear);
1444
1445   { 
1446     'error'     => '',
1447     'svcnum'    => $p->{svcnum},
1448     'beginning' => $p->{beginning},
1449     'ending'    => $p->{ending},
1450     'previous'  => ($previous > $start) ? $previous : $start,
1451     'next'      => ($next < $end) ? $next : $end,
1452     'header'    => $header,
1453     'usage'     => \@usage,
1454   };
1455 }
1456
1457 sub order_pkg {
1458   my $p = shift;
1459
1460   my($context, $session, $custnum) = _custoragent_session_custnum($p);
1461   return { 'error' => $session } if $context eq 'error';
1462
1463   my $search = { 'custnum' => $custnum };
1464   $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
1465   my $cust_main = qsearchs('cust_main', $search )
1466     or return { 'error' => "unknown custnum $custnum" };
1467
1468   my $status = $cust_main->status;
1469   #false laziness w/ClientAPI/Signup.pm
1470
1471   my $cust_pkg = new FS::cust_pkg ( {
1472     'custnum' => $custnum,
1473     'pkgpart' => $p->{'pkgpart'},
1474   } );
1475   my $error = $cust_pkg->check;
1476   return { 'error' => $error } if $error;
1477
1478   my @svc = ();
1479   unless ( $p->{'svcpart'} eq 'none' ) {
1480
1481     my $svcdb;
1482     my $svcpart = '';
1483     if ( $p->{'svcpart'} =~ /^(\d+)$/ ) {
1484       $svcpart = $1;
1485       my $part_svc = qsearchs('part_svc', { 'svcpart' => $svcpart } );
1486       return { 'error' => "Unknown svcpart $svcpart" } unless $part_svc;
1487       $svcdb = $part_svc->svcdb;
1488     } else {
1489       $svcdb = 'svc_acct';
1490     }
1491     $svcpart ||= $cust_pkg->part_pkg->svcpart($svcdb);
1492
1493     my %fields = (
1494       'svc_acct'     => [ qw( username domsvc _password sec_phrase popnum ) ],
1495       'svc_domain'   => [ qw( domain ) ],
1496       'svc_phone'    => [ qw( phonenum pin sip_password phone_name ) ],
1497       'svc_external' => [ qw( id title ) ],
1498       'svc_pbx'      => [ qw( id title ) ],
1499     );
1500   
1501     my $svc_x = "FS::$svcdb"->new( {
1502       'svcpart'   => $svcpart,
1503       map { $_ => $p->{$_} } @{$fields{$svcdb}}
1504     } );
1505     
1506     if ( $svcdb eq 'svc_acct' && exists($p->{"snarf_machine1"}) ) {
1507       my @acct_snarf;
1508       my $snarfnum = 1;
1509       while ( length($p->{"snarf_machine$snarfnum"}) ) {
1510         my $acct_snarf = new FS::acct_snarf ( {
1511           'machine'   => $p->{"snarf_machine$snarfnum"},
1512           'protocol'  => $p->{"snarf_protocol$snarfnum"},
1513           'username'  => $p->{"snarf_username$snarfnum"},
1514           '_password' => $p->{"snarf_password$snarfnum"},
1515         } );
1516         $snarfnum++;
1517         push @acct_snarf, $acct_snarf;
1518       }
1519       $svc_x->child_objects( \@acct_snarf );
1520     }
1521     
1522     my $y = $svc_x->setdefault; # arguably should be in new method
1523     return { 'error' => $y } if $y && !ref($y);
1524   
1525     $error = $svc_x->check;
1526     return { 'error' => $error } if $error;
1527
1528     push @svc, $svc_x;
1529
1530   }
1531
1532   use Tie::RefHash;
1533   tie my %hash, 'Tie::RefHash';
1534   %hash = ( $cust_pkg => \@svc );
1535   #msgcat
1536   $error = $cust_main->order_pkgs( \%hash, 'noexport' => 1 );
1537   return { 'error' => $error } if $error;
1538
1539   my $conf = new FS::Conf;
1540   if ( $conf->exists('signup_server-realtime') ) {
1541
1542     my $bill_error = _do_bop_realtime( $cust_main, $status );
1543
1544     if ($bill_error) {
1545       $cust_pkg->cancel('quiet'=>1);
1546       return $bill_error;
1547     } else {
1548       $cust_pkg->reexport;
1549     }
1550
1551   } else {
1552     $cust_pkg->reexport;
1553   }
1554
1555   my $svcnum = $svc[0] ? $svc[0]->svcnum : '';
1556
1557   return { error=>'', pkgnum=>$cust_pkg->pkgnum, svcnum=>$svcnum };
1558
1559 }
1560
1561 sub change_pkg {
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 $search = { 'custnum' => $custnum };
1568   $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
1569   my $cust_main = qsearchs('cust_main', $search )
1570     or return { 'error' => "unknown custnum $custnum" };
1571
1572   my $status = $cust_main->status;
1573   my $cust_pkg = qsearchs('cust_pkg', { 'pkgnum' => $p->{pkgnum} } )
1574     or return { 'error' => "unknown package $p->{pkgnum}" };
1575
1576   my @newpkg;
1577   my $error = FS::cust_pkg::order( $custnum,
1578                                    [$p->{pkgpart}],
1579                                    [$p->{pkgnum}],
1580                                    \@newpkg,
1581                                  );
1582
1583   my $conf = new FS::Conf;
1584   if ( $conf->exists('signup_server-realtime') ) {
1585
1586     my $bill_error = _do_bop_realtime( $cust_main, $status );
1587
1588     if ($bill_error) {
1589       $newpkg[0]->suspend;
1590       return $bill_error;
1591     } else {
1592       $newpkg[0]->reexport;
1593     }
1594
1595   } else {  
1596     $newpkg[0]->reexport;
1597   }
1598
1599   return { error => '', pkgnum => $cust_pkg->pkgnum };
1600
1601 }
1602
1603 sub order_recharge {
1604   my $p = shift;
1605
1606   my($context, $session, $custnum) = _custoragent_session_custnum($p);
1607   return { 'error' => $session } if $context eq 'error';
1608
1609   my $search = { 'custnum' => $custnum };
1610   $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
1611   my $cust_main = qsearchs('cust_main', $search )
1612     or return { 'error' => "unknown custnum $custnum" };
1613
1614   my $status = $cust_main->status;
1615   my $cust_svc = qsearchs( 'cust_svc', { 'svcnum' => $p->{'svcnum'} } )
1616     or return { 'error' => "unknown service " . $p->{'svcnum'} };
1617
1618   my $svc_x = $cust_svc->svc_x;
1619   my $part_pkg = $cust_svc->cust_pkg->part_pkg;
1620
1621   my %vhash =
1622     map { $_ =~ /^recharge_(.*)$/; $1, $part_pkg->option($_, 1) } 
1623     qw ( recharge_seconds recharge_upbytes recharge_downbytes
1624          recharge_totalbytes );
1625   my $amount = $part_pkg->option('recharge_amount', 1); 
1626   
1627   my ($l, $v, $d) = $cust_svc->label;  # blah
1628   my $pkg = "Recharge $v"; 
1629
1630   my $bill_error = $cust_main->charge($amount, $pkg,
1631      "time: $vhash{seconds}, up: $vhash{upbytes}," . 
1632      "down: $vhash{downbytes}, total: $vhash{totalbytes}",
1633      $part_pkg->taxclass); #meh
1634
1635   my $conf = new FS::Conf;
1636   if ( $conf->exists('signup_server-realtime') && !$bill_error ) {
1637
1638     $bill_error = _do_bop_realtime( $cust_main, $status );
1639
1640     if ($bill_error) {
1641       return $bill_error;
1642     } else {
1643       my $error = $svc_x->recharge (\%vhash);
1644       return { 'error' => $error } if $error;
1645     }
1646
1647   } else {  
1648     my $error = $bill_error;
1649     $error ||= $svc_x->recharge (\%vhash);
1650     return { 'error' => $error } if $error;
1651   }
1652
1653   return { error => '', svc => $cust_svc->part_svc->svc };
1654
1655 }
1656
1657 sub _do_bop_realtime {
1658   my ($cust_main, $status) = (shift, shift);
1659
1660     my $old_balance = $cust_main->balance;
1661
1662     my $bill_error =    $cust_main->bill
1663                      || $cust_main->apply_payments_and_credits
1664                      || $cust_main->realtime_collect('selfservice' => 1);
1665
1666     if (    $cust_main->balance > $old_balance
1667          && $cust_main->balance > 0
1668          && ( $cust_main->payby !~ /^(BILL|DCRD|DCHK)$/ ?
1669               1 : $status eq 'suspended' ) ) {
1670       #this makes sense.  credit is "un-doing" the invoice
1671       my $conf = new FS::Conf;
1672       $cust_main->credit( sprintf("%.2f", $cust_main->balance - $old_balance ),
1673                           'self-service decline',
1674                           'reason_type' => $conf->config('signup_credit_type'),
1675                         );
1676       $cust_main->apply_credits( 'order' => 'newest' );
1677
1678       return { 'error' => '_decline', 'bill_error' => $bill_error };
1679     }
1680
1681     '';
1682 }
1683
1684 sub renew_info {
1685   my $p = shift;
1686
1687   my($context, $session, $custnum) = _custoragent_session_custnum($p);
1688   return { 'error' => $session } if $context eq 'error';
1689
1690   my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1691     or return { 'error' => "unknown custnum $custnum" };
1692
1693   my @cust_pkg = sort { $a->bill <=> $b->bill }
1694                  grep { $_->part_pkg->freq ne '0' }
1695                  $cust_main->ncancelled_pkgs;
1696
1697   #return { 'error' => 'No active packages to renew.' } unless @cust_pkg;
1698
1699   my $total = $cust_main->balance;
1700
1701   my @array = map {
1702                     my $bill = $_->bill;
1703                     $total += $_->part_pkg->base_recur($_, \$bill);
1704                     my $renew_date = $_->part_pkg->add_freq($_->bill);
1705                     {
1706                       'pkgnum'             => $_->pkgnum,
1707                       'amount'             => sprintf('%.2f', $total),
1708                       'bill_date'          => $_->bill,
1709                       'bill_date_pretty'   => time2str('%x', $_->bill),
1710                       'renew_date'         => $renew_date,
1711                       'renew_date_pretty'  => time2str('%x', $renew_date),
1712                       'expire_date'        => $_->expire,
1713                       'expire_date_pretty' => time2str('%x', $_->expire),
1714                     };
1715                   }
1716                   @cust_pkg;
1717
1718   return { 'dates' => \@array };
1719
1720 }
1721
1722 sub payment_info_renew_info {
1723   my $p = shift;
1724   my $renew_info   = renew_info($p);
1725   my $payment_info = payment_info($p);
1726   return { %$renew_info,
1727            %$payment_info,
1728          };
1729 }
1730
1731 sub order_renew {
1732   my $p = shift;
1733
1734   my($context, $session, $custnum) = _custoragent_session_custnum($p);
1735   return { 'error' => $session } if $context eq 'error';
1736
1737   my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1738     or return { 'error' => "unknown custnum $custnum" };
1739
1740   my $date = $p->{'date'};
1741
1742   my $now = time;
1743
1744   #freeside-daily -n -d $date fs_daily $custnum
1745   $cust_main->bill_and_collect( 'time'         => $date,
1746                                 'invoice_time' => $now,
1747                                 'actual_time'  => $now,
1748                                 'check_freq'   => '1d',
1749                               );
1750
1751   return { 'error' => '' };
1752
1753 }
1754
1755 sub suspend_pkg {
1756   my $p = shift;
1757   my $session = _cache->get($p->{'session_id'})
1758     or return { 'error' => "Can't resume session" }; #better error message
1759
1760   my $custnum = $session->{'custnum'};
1761
1762   my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1763     or return { 'error' => "unknown custnum $custnum" };
1764
1765   my $conf = new FS::Conf;
1766   my $reasonnum = 
1767     $conf->config('selfservice-self_suspend_reason', $cust_main->agentnum)
1768       or return { 'error' => 'Permission denied' };
1769
1770   my $pkgnum = $p->{'pkgnum'};
1771
1772   my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
1773                                         'pkgnum'  => $pkgnum,   } )
1774     or return { 'error' => "unknown pkgnum $pkgnum" };
1775
1776   my $error = $cust_pkg->suspend(reason => $reasonnum);
1777   return { 'error' => $error };
1778
1779 }
1780
1781 sub cancel_pkg {
1782   my $p = shift;
1783   my $session = _cache->get($p->{'session_id'})
1784     or return { 'error' => "Can't resume session" }; #better error message
1785
1786   my $custnum = $session->{'custnum'};
1787
1788   my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1789     or return { 'error' => "unknown custnum $custnum" };
1790
1791   my $pkgnum = $p->{'pkgnum'};
1792
1793   my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
1794                                         'pkgnum'  => $pkgnum,   } )
1795     or return { 'error' => "unknown pkgnum $pkgnum" };
1796
1797   my $error = $cust_pkg->cancel('quiet' => 1);
1798   return { 'error' => $error };
1799
1800 }
1801
1802 sub provision_phone {
1803  my $p = shift;
1804  my @bulkdid;
1805  @bulkdid = @{$p->{'bulkdid'}} if $p->{'bulkdid'};
1806
1807  if($p->{'svcnum'} && $p->{'svcnum'} =~ /^\d+$/){
1808       my($context, $session, $custnum) = _custoragent_session_custnum($p);
1809       return { 'error' => $session } if $context eq 'error';
1810     
1811       my $svc_phone = qsearchs('svc_phone', { svcnum => $p->{'svcnum'} });
1812       return { 'error' => 'service not found' } unless $svc_phone;
1813       return { 'error' => 'invalid svcnum' } 
1814         if $svc_phone && $svc_phone->cust_svc->cust_pkg->custnum != $custnum;
1815
1816       $svc_phone->email($p->{'email'}) 
1817         if $svc_phone->email ne $p->{'email'} && $p->{'email'} =~ /^([\w\.\d@]+|)$/;
1818       $svc_phone->forwarddst($p->{'forwarddst'}) 
1819         if $svc_phone->forwarddst ne $p->{'forwarddst'} 
1820             && $p->{'forwarddst'} =~ /^(\d+|)$/;
1821       return { 'error' => $svc_phone->replace };
1822  }
1823
1824 # single DID LNP
1825  unless($p->{'lnp'}) {
1826     $p->{'lnp_desired_due_date'} = parse_datetime($p->{'lnp_desired_due_date'});
1827     $p->{'lnp_status'} = "portingin";
1828     return _provision( 'FS::svc_phone',
1829                   [qw(lnp_desired_due_date lnp_other_provider 
1830                     lnp_other_provider_account phonenum countrycode lnp_status)],
1831                   [qw(phonenum countrycode)],
1832                   $p,
1833                   @_
1834                 );
1835  }
1836
1837 # single DID order
1838  unless (scalar(@bulkdid)) {
1839     return _provision( 'FS::svc_phone',
1840                   [qw(phonenum countrycode)],
1841                   [qw(phonenum countrycode)],
1842                   $p,
1843                   @_
1844                 );
1845  }
1846
1847 # bulk DID order case
1848   my $error;
1849   foreach my $did ( @bulkdid ) {
1850     $did =~ s/[^0-9]//g;
1851     $error = _provision( 'FS::svc_phone',
1852               [qw(phonenum countrycode)],
1853               [qw(phonenum countrycode)],
1854               {
1855                 'pkgnum' => $p->{'pkgnum'},
1856                 'svcpart' => $p->{'svcpart'},
1857                 'phonenum' => $did,
1858                 'countrycode' => $p->{'countrycode'},
1859                 'session_id' => $p->{'session_id'},
1860               }
1861             );
1862     return $error if ($error->{'error'} && length($error->{'error'}) > 1);
1863   }
1864   { 'bulkdid' => [ @bulkdid ], 'svc' => $error->{'svc'} }
1865 }
1866
1867 sub provision_acct {
1868   my $p = shift;
1869   warn "provision_acct called\n"
1870     if $DEBUG;
1871
1872   return { 'error' => gettext('passwords_dont_match') }
1873     if $p->{'_password'} ne $p->{'_password2'};
1874   return { 'error' => gettext('empty_password') }
1875     unless length($p->{'_password'});
1876  
1877   if ($p->{'domsvc'}) {
1878     my %domains = domain_select_hash FS::svc_acct(map { $_ => $p->{$_} }
1879                                                   qw ( svcpart pkgnum ) );
1880     return { 'error' => gettext('invalid_domain') }
1881       unless ($domains{$p->{'domsvc'}});
1882   }
1883
1884   warn "provision_acct calling _provision\n"
1885     if $DEBUG;
1886   _provision( 'FS::svc_acct',
1887               [qw(username _password domsvc)],
1888               [qw(username _password domsvc)],
1889               $p,
1890               @_
1891             );
1892 }
1893
1894 sub provision_external {
1895   my $p = shift;
1896   #_provision( 'FS::svc_external', [qw(id title)], [qw(id title)], $p, @_ );
1897   _provision( 'FS::svc_external',
1898               [],
1899               [qw(id title)],
1900               $p,
1901               @_
1902             );
1903 }
1904
1905 sub _provision {
1906   my( $class, $fields, $return_fields, $p ) = splice(@_, 0, 4);
1907   warn "_provision called for $class\n"
1908     if $DEBUG;
1909
1910   my($context, $session, $custnum) = _custoragent_session_custnum($p);
1911   return { 'error' => $session } if $context eq 'error';
1912
1913   my $search = { 'custnum' => $custnum };
1914   $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
1915   my $cust_main = qsearchs('cust_main', $search )
1916     or return { 'error' => "unknown custnum $custnum" };
1917
1918   my $pkgnum = $p->{'pkgnum'};
1919
1920   warn "searching for custnum $custnum pkgnum $pkgnum\n"
1921     if $DEBUG;
1922   my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
1923                                         'pkgnum'  => $pkgnum,
1924                                                                } )
1925     or return { 'error' => "unknown pkgnum $pkgnum" };
1926
1927   warn "searching for svcpart ". $p->{'svcpart'}. "\n"
1928     if $DEBUG;
1929   my $part_svc = qsearchs('part_svc', { 'svcpart' => $p->{'svcpart'} } )
1930     or return { 'error' => "unknown svcpart $p->{'svcpart'}" };
1931
1932   warn "creating $class record\n"
1933     if $DEBUG;
1934   my $svc_x = $class->new( {
1935     'pkgnum'  => $p->{'pkgnum'},
1936     'svcpart' => $p->{'svcpart'},
1937     map { $_ => $p->{$_} } @$fields
1938   } );
1939   warn "inserting $class record\n"
1940     if $DEBUG;
1941   my $error = $svc_x->insert;
1942
1943   unless ( $error ) {
1944     warn "finding inserted record for svcnum ". $svc_x->svcnum. "\n"
1945       if $DEBUG;
1946     $svc_x = qsearchs($svc_x->table, { 'svcnum' => $svc_x->svcnum })
1947   }
1948
1949   my $return = { 'svc'   => $part_svc->svc,
1950                  'error' => $error,
1951                  map { $_ => $svc_x->get($_) } @$return_fields
1952                };
1953   warn "_provision returning ". Dumper($return). "\n"
1954     if $DEBUG;
1955   return $return;
1956
1957 }
1958
1959 sub part_svc_info {
1960   my $p = shift;
1961
1962   my($context, $session, $custnum) = _custoragent_session_custnum($p);
1963   return { 'error' => $session } if $context eq 'error';
1964
1965   my $search = { 'custnum' => $custnum };
1966   $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
1967   my $cust_main = qsearchs('cust_main', $search )
1968     or return { 'error' => "unknown custnum $custnum" };
1969
1970   my $pkgnum = $p->{'pkgnum'};
1971
1972   my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
1973                                         'pkgnum'  => $pkgnum,
1974                                                                } )
1975     or return { 'error' => "unknown pkgnum $pkgnum" };
1976
1977   my $svcpart = $p->{'svcpart'};
1978
1979   my $pkg_svc = qsearchs('pkg_svc', { 'pkgpart' => $cust_pkg->pkgpart,
1980                                       'svcpart' => $svcpart,           } )
1981     or return { 'error' => "unknown svcpart $svcpart for pkgnum $pkgnum" };
1982   my $part_svc = $pkg_svc->part_svc;
1983
1984   my $conf = new FS::Conf;
1985
1986   my $ret = {
1987     'svc'     => $part_svc->svc,
1988     'svcdb'   => $part_svc->svcdb,
1989     'pkgnum'  => $pkgnum,
1990     'svcpart' => $svcpart,
1991     'custnum' => $custnum,
1992
1993     'security_phrase' => 0, #XXX !
1994     'svc_acct_pop'    => [], #XXX !
1995     'popnum'          => '',
1996     'init_popstate'   => '',
1997     'popac'           => '',
1998     'acstate'         => '',
1999
2000     'small_custview' =>
2001       small_custview( $cust_main, $conf->config('countrydefault') ),
2002
2003   };
2004
2005   if ($p->{'svcnum'} && $p->{'svcnum'} =~ /^\d+$/ 
2006                      && $ret->{'svcdb'} eq 'svc_phone') {
2007         $ret->{'svcnum'} = $p->{'svcnum'};
2008         my $svc_phone = qsearchs('svc_phone', { svcnum => $p->{'svcnum'} });
2009         if ( $svc_phone && $svc_phone->cust_svc->cust_pkg->custnum == $custnum ) {
2010             $ret->{'email'} = $svc_phone->email;
2011             $ret->{'forwarddst'} = $svc_phone->forwarddst;
2012         }
2013   }
2014
2015   $ret;
2016 }
2017
2018 sub unprovision_svc {
2019   my $p = shift;
2020
2021   my($context, $session, $custnum) = _custoragent_session_custnum($p);
2022   return { 'error' => $session } if $context eq 'error';
2023
2024   my $search = { 'custnum' => $custnum };
2025   $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2026   my $cust_main = qsearchs('cust_main', $search )
2027     or return { 'error' => "unknown custnum $custnum" };
2028
2029   my $svcnum = $p->{'svcnum'};
2030
2031   my $cust_svc = qsearchs('cust_svc', { 'svcnum'  => $svcnum, } )
2032     or return { 'error' => "unknown svcnum $svcnum" };
2033
2034   return { 'error' => "Service $svcnum does not belong to customer $custnum" }
2035     unless $cust_svc->cust_pkg->custnum == $custnum;
2036
2037   my $conf = new FS::Conf;
2038
2039   return { 'svc'   => $cust_svc->part_svc->svc,
2040            'error' => $cust_svc->cancel,
2041            'small_custview' =>
2042              small_custview( $cust_main, $conf->config('countrydefault') ),
2043          };
2044
2045 }
2046
2047 sub myaccount_passwd {
2048   my $p = shift;
2049   my($context, $session, $custnum) = _custoragent_session_custnum($p);
2050   return { 'error' => $session } if $context eq 'error';
2051
2052   return { 'error' => "New passwords don't match." }
2053     if $p->{'new_password'} ne $p->{'new_password2'};
2054
2055   return { 'error' => 'Enter new password' }
2056     unless length($p->{'new_password'});
2057
2058   #my $search = { 'custnum' => $custnum };
2059   #$search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2060   $custnum =~ /^(\d+)$/ or die "illegal custnum";
2061   my $search = " AND custnum = $1";
2062   $search .= " AND agentnum = ". $session->{'agentnum'} if $context eq 'agent';
2063
2064   my $svc_acct = qsearchs( {
2065     'table'     => 'svc_acct',
2066     'addl_from' => 'LEFT JOIN cust_svc  USING ( svcnum  ) '.
2067                    'LEFT JOIN cust_pkg  USING ( pkgnum  ) '.
2068                    'LEFT JOIN cust_main USING ( custnum ) ',
2069     'hashref'   => { 'svcnum' => $p->{'svcnum'}, },
2070     'extra_sql' => $search, #important
2071   } )
2072     or return { 'error' => "Service not found" };
2073
2074   $svc_acct->_password($p->{'new_password'});
2075   my $error = $svc_acct->replace();
2076
2077   my($label, $value) = $svc_acct->cust_svc->label;
2078
2079   return { 'error' => $error,
2080            'label' => $label,
2081            'value' => $value,
2082          };
2083
2084 }
2085
2086 sub create_ticket {
2087   my $p = shift;
2088   my($context, $session, $custnum) = _custoragent_session_custnum($p);
2089   return { 'error' => $session } if $context eq 'error';
2090
2091   warn "$me create_ticket: initializing ticket system\n" if $DEBUG;
2092   FS::TicketSystem->init();
2093
2094   my $conf = new FS::Conf;
2095   my $queue = $p->{'queue'}
2096               || $conf->config('ticket_system-selfservice_queueid')
2097               || $conf->config('ticket_system-default_queueid');
2098
2099   warn "$me create_ticket: creating ticket\n" if $DEBUG;
2100   my $err_or_ticket = FS::TicketSystem->create_ticket(
2101     '', #create RT session based on FS CurrentUser (fs_selfservice)
2102     'queue'   => $queue,
2103     'custnum' => $custnum,
2104     'svcnum'  => $session->{'svcnum'},
2105     map { $_ => $p->{$_} } qw( requestor cc subject message mime_type )
2106   );
2107
2108   if ( ref($err_or_ticket) ) {
2109     warn "$me create_ticket: successful: ". $err_or_ticket->id. "\n"
2110       if $DEBUG;
2111     return { 'error'     => '',
2112              'ticket_id' => $err_or_ticket->id,
2113            };
2114   } else {
2115     warn "$me create_ticket: unsuccessful: $err_or_ticket\n"
2116       if $DEBUG;
2117     return { 'error' => $err_or_ticket };
2118   }
2119
2120
2121 }
2122
2123 sub did_report {
2124   my $p = shift;
2125   my($context, $session, $custnum) = _custoragent_session_custnum($p);
2126   return { 'error' => $session } if $context eq 'error';
2127  
2128   return { error => 'requested format not implemented' } 
2129     unless ($p->{'format'} eq 'csv' || $p->{'format'} eq 'xls');
2130
2131   my $conf = new FS::Conf;
2132   my $age_threshold = 0;
2133   $age_threshold = time() - $conf->config('selfservice-recent-did-age')
2134     if ($p->{'recentonly'} && $conf->exists('selfservice-recent-did-age'));
2135
2136   my $search = { 'custnum' => $custnum };
2137   $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2138   my $cust_main = qsearchs('cust_main', $search )
2139     or return { 'error' => "unknown custnum $custnum" };
2140
2141 # does it make more sense to just run one sql query for this instead of all the
2142 # insanity below? would increase performance greately for large data sets?
2143   my @svc_phone = ();
2144   foreach my $cust_pkg ( $cust_main->ncancelled_pkgs ) {
2145         my @part_svc = $cust_pkg->part_svc;
2146         foreach my $part_svc ( @part_svc ) {
2147             if($part_svc->svcdb eq 'svc_phone'){
2148                 my @cust_pkg_svc = @{$part_svc->cust_pkg_svc};
2149                 foreach my $cust_pkg_svc ( @cust_pkg_svc ) {
2150                     push @svc_phone, $cust_pkg_svc->svc_x
2151                         if $cust_pkg_svc->date_inserted >= $age_threshold;
2152                 }
2153             }
2154         }
2155   }
2156
2157   my $csv;
2158   my $xls;
2159   my($xls_r,$xls_c) = (0,0);
2160   my $xls_workbook;
2161   my $content = '';
2162   my @fields = qw( countrycode phonenum pin sip_password phone_name );
2163   if($p->{'format'} eq 'csv') {
2164     $csv = new Text::CSV_XS { 'always_quote' => 1,
2165                                  'eol'          => "\n",
2166                                 };
2167     return { 'error' => 'Unable to create CSV' } unless $csv->combine(@fields);
2168     $content .= $csv->string;
2169   }
2170   elsif($p->{'format'} eq 'xls') {
2171     my $XLS1 = new IO::Scalar \$content;
2172     $xls_workbook = Spreadsheet::WriteExcel->new($XLS1) 
2173         or return { 'error' => "Error opening .xls file: $!" };
2174     $xls = $xls_workbook->add_worksheet('DIDs');
2175     foreach ( @fields ) {
2176         $xls->write(0,$xls_c++,$_);
2177     }
2178     $xls_r++;
2179   }
2180
2181   foreach my $svc_phone ( @svc_phone ) {
2182     my @cols = map { $svc_phone->$_ } @fields;
2183     if($p->{'format'} eq 'csv') {
2184         return { 'error' => 'Unable to create CSV' } 
2185             unless $csv->combine(@cols);
2186         $content .= $csv->string;
2187     }
2188     elsif($p->{'format'} eq 'xls') {
2189         $xls_c = 0;
2190         foreach ( @cols ) {
2191             $xls->write($xls_r,$xls_c++,$_);
2192         }
2193         $xls_r++;
2194     }
2195   }
2196
2197   $xls_workbook->close() if $p->{'format'} eq 'xls';
2198   
2199   { content => $content, format => $p->{'format'}, };
2200 }
2201
2202 sub get_ticket {
2203   my $p = shift;
2204   my($context, $session, $custnum) = _custoragent_session_custnum($p);
2205   return { 'error' => $session } if $context eq 'error';
2206
2207   warn "$me get_ticket: initializing ticket system\n" if $DEBUG;
2208   FS::TicketSystem->init();
2209   return { 'error' => 'get_ticket configuration error' }
2210     if $FS::TicketSystem::system ne 'RT_Internal';
2211
2212   # check existence and ownership as part of this
2213   warn "$me get_ticket: fetching ticket\n" if $DEBUG;
2214   my $rt_session = FS::TicketSystem->session('');
2215   my $Ticket = FS::TicketSystem->get_ticket_object(
2216     $rt_session, 
2217     ticket_id => $p->{'ticket_id'},
2218     custnum => $custnum
2219   );
2220   return { 'error' => 'ticket not found' } if !$Ticket;
2221
2222   if ( length( $p->{'subject'} || '' ) ) {
2223     # subject change
2224     if ( $p->{'subject'} ne $Ticket->Subject ) {
2225       my ($val, $msg) = $Ticket->SetSubject($p->{'subject'});
2226       return { 'error' => "unable to set subject: $msg" } if !$val;
2227     }
2228   }
2229
2230   if(length($p->{'reply'})) {
2231     my @err_or_res = FS::TicketSystem->correspond_ticket(
2232       $rt_session,
2233       'ticket_id' => $p->{'ticket_id'},
2234       'content' => $p->{'reply'},
2235     );
2236
2237     return { 'error' => 'unable to reply to ticket' } 
2238     unless ( $err_or_res[0] != 0 && defined $err_or_res[2] );
2239   }
2240
2241   warn "$me get_ticket: getting ticket history\n" if $DEBUG;
2242   my $err_or_ticket = FS::TicketSystem->get_ticket(
2243     $rt_session,
2244     'ticket_id' => $p->{'ticket_id'},
2245   );
2246
2247   if ( !ref($err_or_ticket) ) { # there is no way this should ever happen
2248     warn "$me get_ticket: unsuccessful: $err_or_ticket\n"
2249       if $DEBUG;
2250     return { 'error' => $err_or_ticket };
2251   }
2252
2253   my @custs = @{$err_or_ticket->{'custs'}};
2254   my @txns = @{$err_or_ticket->{'txns'}};
2255   my @filtered_txns;
2256
2257   # superseded by check in get_ticket_object
2258   #return { 'error' => 'invalid ticket requested' } 
2259   #unless grep($_ eq $custnum, @custs);
2260
2261   foreach my $txn ( @txns ) {
2262     push @filtered_txns, $txn 
2263     if ($txn->{'type'} eq 'EmailRecord' 
2264       || $txn->{'type'} eq 'Correspond'
2265       || $txn->{'type'} eq 'Create');
2266   }
2267
2268   warn "$me get_ticket: successful: \n"
2269   if $DEBUG;
2270   return { 'error'     => '',
2271     'transactions' => \@filtered_txns,
2272     'ticket_fields' => $err_or_ticket->{'fields'},
2273     'ticket_id' => $p->{'ticket_id'},
2274   };
2275 }
2276
2277 sub adjust_ticket_priority {
2278   my $p = shift;
2279   my($context, $session, $custnum) = _custoragent_session_custnum($p);
2280   return { 'error' => $session } if $context eq 'error';
2281
2282   warn "$me adjust_ticket_priority: initializing ticket system\n" if $DEBUG;
2283   FS::TicketSystem->init;
2284   my $ss_priority = FS::TicketSystem->selfservice_priority;
2285
2286   return { 'error' => 'adjust_ticket_priority configuration error' }
2287     if $FS::TicketSystem::system ne 'RT_Internal'
2288       or !$ss_priority;
2289
2290   my $values = $p->{'values'}; #hashref, id => priority value
2291   my %ticket_error;
2292
2293   foreach my $id (keys %$values) {
2294     warn "$me adjust_ticket_priority: fetching ticket $id\n" if $DEBUG;
2295     my $Ticket = FS::TicketSystem->get_ticket_object('',
2296       'ticket_id' => $id,
2297       'custnum'   => $custnum,
2298     );
2299     if ( !$Ticket ) {
2300       $ticket_error{$id} = 'ticket not found';
2301       next;
2302     }
2303     
2304   # RT API stuff--would we gain anything by wrapping this in FS::TicketSystem?
2305   # We're not going to implement it for RT_External.
2306     my $old_value = $Ticket->FirstCustomFieldValue($ss_priority);
2307     my $new_value = $values->{$id};
2308     next if $old_value eq $new_value;
2309
2310     warn "$me adjust_ticket_priority: updating ticket $id\n" if $DEBUG;
2311
2312     # AddCustomFieldValue works fine (replacing any existing value) if it's 
2313     # a single-valued custom field, which it should be.  If it's not, you're 
2314     # doing something wrong.
2315     my ($val, $msg);
2316     if ( length($new_value) ) {
2317       ($val, $msg) = $Ticket->AddCustomFieldValue( 
2318         Field => $ss_priority,
2319         Value => $new_value,
2320       );
2321     }
2322     else {
2323       ($val, $msg) = $Ticket->DeleteCustomFieldValue(
2324         Field => $ss_priority,
2325         Value => $old_value,
2326       );
2327     }
2328
2329     $ticket_error{$id} = $msg if !$val;
2330     warn "$me adjust_ticket_priority: $id: $msg\n" if $DEBUG and !$val;
2331   }
2332   return { 'error' => '',
2333            'ticket_error' => \%ticket_error,
2334            %{ customer_info($p) } # send updated customer info back
2335          }
2336 }
2337
2338 #--
2339
2340 sub _custoragent_session_custnum {
2341   my $p = shift;
2342
2343   my($context, $session, $custnum);
2344   if ( $p->{'session_id'} ) {
2345
2346     $context = 'customer';
2347     $session = _cache->get($p->{'session_id'})
2348       or return ( 'error' => "Can't resume session" ); #better error message
2349     $custnum = $session->{'custnum'};
2350
2351   } elsif ( $p->{'agent_session_id'} ) {
2352
2353     $context = 'agent';
2354     my $agent_cache = new FS::ClientAPI_SessionCache( {
2355       'namespace' => 'FS::ClientAPI::Agent',
2356     } );
2357     $session = $agent_cache->get($p->{'agent_session_id'})
2358       or return ( 'error' => "Can't resume session" ); #better error message
2359     $custnum = $p->{'custnum'};
2360
2361   } else {
2362     $context = 'error';
2363     return ( 'error' => "Can't resume session" ); #better error message
2364   }
2365
2366   ($context, $session, $custnum);
2367
2368 }
2369
2370 1;
2371