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     'paynum_ref'  => \$paynum,
805     %$validate,
806   );
807   return { 'error' => $error } if $error;
808
809   $cust_main->apply_payments;
810
811   if ( $validate->{'save'} ) {
812     my $new = new FS::cust_main { $cust_main->hash };
813     if ($validate->{'payby'} eq 'CARD' || $validate->{'payby'} eq 'DCRD') {
814       $new->set( $_ => $validate->{$_} )
815         foreach qw( payname paystart_month paystart_year payissue payip
816                     address1 address2 city state zip country );
817       $new->set( 'payby' => $validate->{'auto'} ? 'CARD' : 'DCRD' );
818     } elsif ($payby eq 'CHEK' || $payby eq 'DCHK') {
819       $new->set( $_ => $validate->{$_} )
820         foreach qw( payname payip paytype paystate
821                     stateid stateid_state );
822       $new->set( 'payby' => $validate->{'auto'} ? 'CHEK' : 'DCHK' );
823     }
824     $new->set( 'payinfo' => $cust_main->card_token || $validate->{'payinfo'} );
825     $new->set( 'paydate' => $validate->{'paydate'} );
826     my $error = $new->replace($cust_main);
827     if ( $error ) {
828       #no, this causes customers to process their payments again
829       #return { 'error' => $error };
830       #XXX just warn verosely for now so i can figure out how these happen in
831       # the first place, eventually should redirect them to the "change
832       #address" page but indicate the payment did process??
833       delete($validate->{'payinfo'}); #don't want to log this!
834       warn "WARNING: error changing customer info when processing payment (not returning to customer as a processing error): $error\n".
835            "NEW: ". Dumper($new)."\n".
836            "OLD: ". Dumper($cust_main)."\n".
837            "PACKET: ". Dumper($validate)."\n";
838     #} else {
839       #not needed...
840       #$cust_main = $new;
841     }
842   }
843
844   my $cust_pay = '';
845   my $receipt_html = '';
846   if ($paynum) {
847       # currently supported for realtime CC only; send receipt data to SS
848       $cust_pay = qsearchs('cust_pay', { 'paynum' => $paynum } );
849       if($cust_pay) {
850         $receipt_html = qq!
851 <TABLE BGCOLOR="#cccccc" BORDER=0 CELLSPACING=2>
852
853 <TR>
854   <TD ALIGN="right">Payment#</TD>
855   <TD BGCOLOR="#FFFFFF"><B>! . $cust_pay->paynum . qq!</B></TD>
856 </TR>
857
858 <TR>
859   <TD ALIGN="right">Date</TD>
860
861   <TD BGCOLOR="#FFFFFF"><B>! . 
862         time2str("%a&nbsp;%b&nbsp;%o,&nbsp;%Y&nbsp;%r", $cust_pay->_date)
863                                                             . qq!</B></TD>
864 </TR>
865
866
867 <TR>
868   <TD ALIGN="right">Amount</TD>
869   <TD BGCOLOR="#FFFFFF"><B>! . sprintf('%.2f', $cust_pay->paid) . qq!</B></TD>
870
871 </TR>
872
873 <TR>
874   <TD ALIGN="right">Payment method</TD>
875   <TD BGCOLOR="#FFFFFF"><B>! . $cust_pay->payby_name .' #'. $cust_pay->paymask
876                                                                 . qq!</B></TD>
877 </TR>
878
879 </TABLE>
880 !;
881       }
882   }
883
884   if ( $cust_pay ) {
885
886     my($gw, $auth, $order) = split(':', $cust_pay->paybatch);
887
888     return {
889       'error'        => '',
890       'amount'       => sprintf('%.2f', $cust_pay->paid),
891       'date'         => $cust_pay->_date,
892       'date_pretty'  => time2str('%Y-%m-%d', $cust_pay->_date),
893       'time_pretty'  => time2str('%T', $cust_pay->_date),
894       'auth_num'     => $auth,
895       'order_num'    => $order,
896       'receipt_html' => $receipt_html,
897     };
898
899   } else {
900
901     return {
902       'error'        => '',
903       'receipt_html' => '',
904     };
905
906   }
907
908 }
909
910 sub realtime_collect {
911   my $p = shift;
912
913   my $session = _cache->get($p->{'session_id'})
914     or return { 'error' => "Can't resume session" }; #better error message
915
916   my $custnum = $session->{'custnum'};
917
918   my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
919     or return { 'error' => "unknown custnum $custnum" };
920
921   my $amount;
922   if ( $p->{'amount'} ) {
923     $amount = $p->{'amount'};
924   }
925   elsif ( $session->{'pkgnum'} ) {
926     $amount = $cust_main->balance_pkgnum( $session->{'pkgnum'} );
927   }
928   else {
929     $amount = $cust_main->balance;
930   }
931
932   my $error = $cust_main->realtime_collect(
933     'method'     => $p->{'method'},
934     'amount'     => $amount,
935     'pkgnum'     => $session->{'pkgnum'},
936     'session_id' => $p->{'session_id'},
937     'apply'      => 1,
938     'selfservice'=> 1,
939   );
940   return { 'error' => $error } unless ref( $error );
941
942   return { 'error' => '', amount => $amount, %$error };
943 }
944
945 sub process_payment_order_pkg {
946   my $p = shift;
947
948   my $hr = process_payment($p);
949   return $hr if $hr->{'error'};
950
951   order_pkg($p);
952 }
953
954 sub process_payment_order_renew {
955   my $p = shift;
956
957   my $hr = process_payment($p);
958   return $hr if $hr->{'error'};
959
960   order_renew($p);
961 }
962
963 sub process_prepay {
964
965   my $p = shift;
966
967   my $session = _cache->get($p->{'session_id'})
968     or return { 'error' => "Can't resume session" }; #better error message
969
970   my %return;
971
972   my $custnum = $session->{'custnum'};
973
974   my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
975     or return { 'error' => "unknown custnum $custnum" };
976
977   my( $amount, $seconds, $upbytes, $downbytes, $totalbytes ) = ( 0, 0, 0, 0, 0 );
978   my $error = $cust_main->recharge_prepay( $p->{'prepaid_cardnum'},
979                                            \$amount,
980                                            \$seconds,
981                                            \$upbytes,
982                                            \$downbytes,
983                                            \$totalbytes,
984                                          );
985
986   return { 'error' => $error } if $error;
987
988   return { 'error'     => '',
989            'amount'    => $amount,
990            'seconds'   => $seconds,
991            'duration'  => duration_exact($seconds),
992            'upbytes'   => $upbytes,
993            'upload'    => FS::UI::bytecount::bytecount_unexact($upbytes),
994            'downbytes' => $downbytes,
995            'download'  => FS::UI::bytecount::bytecount_unexact($downbytes),
996            'totalbytes'=> $totalbytes,
997            'totalload' => FS::UI::bytecount::bytecount_unexact($totalbytes),
998          };
999
1000 }
1001
1002 sub invoice {
1003   my $p = shift;
1004   my $session = _cache->get($p->{'session_id'})
1005     or return { 'error' => "Can't resume session" }; #better error message
1006
1007   my $custnum = $session->{'custnum'};
1008
1009   my $invnum = $p->{'invnum'};
1010
1011   my $cust_bill = qsearchs('cust_bill', { 'invnum'  => $invnum,
1012                                           'custnum' => $custnum } )
1013     or return { 'error' => "Can't find invnum" };
1014
1015   #my %return;
1016
1017   return { 'error'        => '',
1018            'invnum'       => $invnum,
1019            'invoice_text' => join('', $cust_bill->print_text ),
1020            'invoice_html' => $cust_bill->print_html( { unsquelch_cdr => 1 } ),
1021          };
1022
1023 }
1024
1025 sub invoice_pdf {
1026   my $p = shift;
1027   my $session = _cache->get($p->{'session_id'})
1028     or return { 'error' => "Can't resume session" }; #better error message
1029
1030   my $custnum = $session->{'custnum'};
1031
1032   my $invnum = $p->{'invnum'};
1033
1034   my $cust_bill = qsearchs('cust_bill', { 'invnum'  => $invnum,
1035                                           'custnum' => $custnum } )
1036     or return { 'error' => "Can't find invnum" };
1037
1038   #my %return;
1039
1040   return { 'error'       => '',
1041            'invnum'      => $invnum,
1042            'invoice_pdf' => $cust_bill->print_pdf( { unsquelch_cdr => 1 } ),
1043          };
1044
1045 }
1046
1047 sub invoice_logo {
1048   my $p = shift;
1049
1050   #sessioning for this?  how do we get the session id to the backend invoice
1051   # template so it can add it to the link, blah
1052
1053   my $agentnum = '';
1054   if ( $p->{'invnum'} ) {
1055     my $cust_bill = qsearchs('cust_bill', { 'invnum' => $p->{'invnum'} } )
1056       or return { 'error' => 'unknown invnum' };
1057     $agentnum = $cust_bill->cust_main->agentnum;
1058   }
1059
1060   my $templatename = $p->{'template'} || $p->{'templatename'};
1061
1062   #false laziness-ish w/view/cust_bill-logo.cgi
1063
1064   my $conf = new FS::Conf;
1065   if ( $templatename =~ /^([^\.\/]*)$/ && $conf->exists("logo_$1.png") ) {
1066     $templatename = "_$1";
1067   } else {
1068     $templatename = '';
1069   }
1070
1071   my $filename = "logo$templatename.png";
1072
1073   return { 'error'        => '',
1074            'logo'         => $conf->config_binary($filename, $agentnum),
1075            'content_type' => 'image/png', #should allow gif, jpg too
1076          };
1077 }
1078
1079
1080 sub list_invoices {
1081   my $p = shift;
1082   my $session = _cache->get($p->{'session_id'})
1083     or return { 'error' => "Can't resume session" }; #better error message
1084
1085   my $custnum = $session->{'custnum'};
1086
1087   my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1088     or return { 'error' => "unknown custnum $custnum" };
1089
1090   my @cust_bill = $cust_main->cust_bill;
1091
1092   my $balance = 0;
1093
1094   return  { 'error'       => '',
1095             'balance'     => $cust_main->balance,
1096             'invoices'    => [
1097               map {
1098                     my $owed = $_->owed;
1099                     $balance += $owed;
1100                     +{ 'invnum'     => $_->invnum,
1101                        '_date'      => $_->_date,
1102                        'date'       => time2str("%b %o, %Y", $_->_date),
1103                        'date_short' => time2str("%m-%d-%Y",  $_->_date),
1104                        'previous'   => sprintf('%.2f', ($_->previous)[0]),
1105                        'charged'    => sprintf('%.2f', $_->charged),
1106                        'owed'       => sprintf('%.2f', $owed),
1107                        'balance'    => sprintf('%.2f', $balance),
1108                      }
1109                   }
1110                   @cust_bill
1111             ]
1112           };
1113 }
1114
1115 sub cancel {
1116   my $p = shift;
1117   my $session = _cache->get($p->{'session_id'})
1118     or return { 'error' => "Can't resume session" }; #better error message
1119
1120   my $custnum = $session->{'custnum'};
1121
1122   my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1123     or return { 'error' => "unknown custnum $custnum" };
1124
1125   my @errors = $cust_main->cancel( 'quiet'=>1 );
1126
1127   my $error = scalar(@errors) ? join(' / ', @errors) : '';
1128
1129   return { 'error' => $error };
1130
1131 }
1132
1133 sub list_pkgs {
1134   my $p = shift;
1135
1136   my($context, $session, $custnum) = _custoragent_session_custnum($p);
1137   return { 'error' => $session } if $context eq 'error';
1138
1139   my $search = { 'custnum' => $custnum };
1140   $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
1141   my $cust_main = qsearchs('cust_main', $search )
1142     or return { 'error' => "unknown custnum $custnum" };
1143
1144   my $conf = new FS::Conf;
1145   
1146 # the duplication below is necessary:
1147 # 1. to maintain the current buggy behaviour wrt the cust_pkg and part_pkg
1148 # hashes overwriting each other (setup and no_auto fields). Fixing that is a
1149 # non-backwards-compatible change breaking the software of anyone using the API
1150 # instead of the stock selfservice
1151 # 2. to return cancelled packages as well - for wholesale and non-wholesale
1152   if( $conf->exists('selfservice_server-view-wholesale') ) {
1153     return { 'svcnum'   => $session->{'svcnum'},
1154             'custnum'  => $custnum,
1155             'cust_pkg' => [ map {
1156                           { $_->hash,
1157                             part_pkg => [ map $_->hashref, $_->part_pkg ],
1158                             part_svc =>
1159                               [ map $_->hashref, $_->available_part_svc ],
1160                             cust_svc => 
1161                               [ map { my $ref = { $_->hash,
1162                                                   label => [ $_->label ],
1163                                                 };
1164                                       $ref->{_password} = $_->svc_x->_password
1165                                         if $context eq 'agent'
1166                                         && $conf->exists('agent-showpasswords')
1167                                         && $_->part_svc->svcdb eq 'svc_acct';
1168                                       $ref;
1169                                     } $_->cust_svc
1170                               ],
1171                           };
1172                         } $cust_main->cust_pkg
1173                   ],
1174     'small_custview' =>
1175       small_custview( $cust_main, $conf->config('countrydefault') ),
1176     'wholesale_view' => 1,
1177     'login_svcpart' => [ $conf->config('selfservice_server-login_svcpart') ],
1178     'date_format' => $conf->config('date_format') || '%m/%d/%Y',
1179     'lnp' => $conf->exists('svc_phone-lnp'),
1180       };
1181   }
1182
1183   { 'svcnum'   => $session->{'svcnum'},
1184     'custnum'  => $custnum,
1185     'cust_pkg' => [ map {
1186                           my $primary_cust_svc = $_->primary_cust_svc;
1187                           +{ $_->hash,
1188                             $_->part_pkg->hash,
1189                             status => $_->status,
1190                             part_svc =>
1191                               [ map $_->hashref, $_->available_part_svc ],
1192                             cust_svc => 
1193                               [ map { my $ref = { $_->hash,
1194                                                   label => [ $_->label ],
1195                                                 };
1196                                       $ref->{_password} = $_->svc_x->_password
1197                                         if $context eq 'agent'
1198                                         && $conf->exists('agent-showpasswords')
1199                                         && $_->part_svc->svcdb eq 'svc_acct';
1200                                       $ref->{svchash} = { $_->svc_x->hash } if 
1201                                         $_->part_svc->svcdb eq 'svc_phone';
1202                                       $ref->{svchash}->{svcpart} =  $_->part_svc->svcpart
1203                                         if $_->part_svc->svcdb eq 'svc_phone'; # hack
1204                                       $ref;
1205                                     } $_->cust_svc
1206                               ],
1207                             primary_cust_svc =>
1208                               $primary_cust_svc
1209                                 ? { $primary_cust_svc->hash,
1210                                     label => [ $primary_cust_svc->label ],
1211                                     finger => $primary_cust_svc->svc_x->finger, #uuh
1212                                     $primary_cust_svc->part_svc->hash,
1213                                   }
1214                                 : {}, #'' ?
1215                           };
1216                         } $cust_main->ncancelled_pkgs
1217                   ],
1218     'small_custview' =>
1219       small_custview( $cust_main, $conf->config('countrydefault') ),
1220   };
1221
1222 }
1223
1224 sub list_svcs {
1225   my $p = shift;
1226
1227   my($context, $session, $custnum) = _custoragent_session_custnum($p);
1228   return { 'error' => $session } if $context eq 'error';
1229
1230   my $search = { 'custnum' => $custnum };
1231   $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
1232   my $cust_main = qsearchs('cust_main', $search )
1233     or return { 'error' => "unknown custnum $custnum" };
1234
1235   my @cust_svc = ();
1236   #foreach my $cust_pkg ( $cust_main->ncancelled_pkgs ) {
1237   foreach my $cust_pkg ( $p->{'ncancelled'} 
1238                          ? $cust_main->ncancelled_pkgs
1239                          : $cust_main->unsuspended_pkgs ) {
1240     next if $session->{'pkgnum'} && $cust_pkg->pkgnum != $session->{'pkgnum'};
1241     push @cust_svc, @{[ $cust_pkg->cust_svc ]}; #@{[ ]} to force array context
1242   }
1243   if ( $p->{'svcdb'} ) {
1244     my $svcdb = ref($p->{'svcdb'}) eq 'HASH'
1245                   ? $p->{'svcdb'}
1246                   : ref($p->{'svcdb'}) eq 'ARRAY'
1247                     ? { map { $_=>1 } @{ $p->{'svcdb'} } }
1248                     : { $p->{'svcdb'} => 1 };
1249     @cust_svc = grep $svcdb->{ $_->part_svc->svcdb }, @cust_svc
1250   }
1251
1252   #@svc_x = sort { $a->domain cmp $b->domain || $a->username cmp $b->username }
1253   #              @svc_x;
1254
1255     my $conf = new FS::Conf;
1256
1257   { 
1258     'svcnum'   => $session->{'svcnum'},
1259     'custnum'  => $custnum,
1260     'date_format' => $conf->config('date_format') || '%m/%d/%Y',
1261     'view_usage_nodomain' => $conf->exists('selfservice-view_usage_nodomain'),
1262     'svcs'     => [
1263       map { 
1264             my $svc_x = $_->svc_x;
1265             my($label, $value) = $_->label;
1266             my $svcdb = $_->part_svc->svcdb;
1267             my $part_pkg = $_->cust_pkg->part_pkg;
1268
1269             my %hash = (
1270               'svcnum' => $_->svcnum,
1271               'svcdb'  => $svcdb,
1272               'label'  => $label,
1273               'value'  => $value,
1274             );
1275
1276             if ( $svcdb eq 'svc_acct' ) {
1277               %hash = (
1278                 %hash,
1279                 'username'   => $svc_x->username,
1280                 'email'      => $svc_x->email,
1281                 'seconds'    => $svc_x->seconds,
1282                 'upbytes'    => display_bytecount($svc_x->upbytes),
1283                 'downbytes'  => display_bytecount($svc_x->downbytes),
1284                 'totalbytes' => display_bytecount($svc_x->totalbytes),
1285
1286                 'recharge_amount'  => $part_pkg->option('recharge_amount',1),
1287                 'recharge_seconds' => $part_pkg->option('recharge_seconds',1),
1288                 'recharge_upbytes'    =>
1289                   display_bytecount($part_pkg->option('recharge_upbytes',1)),
1290                 'recharge_downbytes'  =>
1291                   display_bytecount($part_pkg->option('recharge_downbytes',1)),
1292                 'recharge_totalbytes' =>
1293                   display_bytecount($part_pkg->option('recharge_totalbytes',1)),
1294                 # more...
1295               );
1296
1297             } elsif ( $svcdb eq 'svc_phone' || $svcdb eq 'svc_port' ) {
1298               %hash = (
1299                 %hash,
1300               );
1301             }
1302
1303             \%hash;
1304           }
1305           @cust_svc
1306     ],
1307   };
1308
1309 }
1310
1311 sub port_graph {
1312   my $p = shift;
1313   _usage_details( \&_port_graph, $p,
1314                   'svcdb' => 'svc_port',
1315                 );
1316 }
1317
1318 sub _port_graph {
1319   my($svc_port, $begin, $end) = @_;
1320   my @usage = ();
1321   my $pngOrError = $svc_port->graph_png( start=>$begin, end=> $end );
1322   push @usage, { 'png' => $pngOrError };
1323   (@usage);
1324 }
1325
1326 sub _list_svc_usage {
1327   my($svc_acct, $begin, $end) = @_;
1328   my @usage = ();
1329   foreach my $part_export ( 
1330     map { qsearch ( 'part_export', { 'exporttype' => $_ } ) }
1331     qw( sqlradius sqlradius_withdomain )
1332   ) {
1333     push @usage, @ { $part_export->usage_sessions($begin, $end, $svc_acct) };
1334   }
1335   (@usage);
1336 }
1337
1338 sub list_svc_usage {
1339   _usage_details(\&_list_svc_usage, @_);
1340 }
1341
1342 sub _list_support_usage {
1343   my($svc_acct, $begin, $end) = @_;
1344   my @usage = ();
1345   foreach ( grep { $begin <= $_->_date && $_->_date <= $end }
1346             qsearch('acct_rt_transaction', { 'svcnum' => $svc_acct->svcnum })
1347           ) {
1348     push @usage, { 'seconds'  => $_->seconds,
1349                    'support'  => $_->support,
1350                    '_date'    => $_->_date,
1351                    'id'       => $_->transaction_id,
1352                    'creator'  => $_->creator,
1353                    'subject'  => $_->subject,
1354                    'status'   => $_->status,
1355                    'ticketid' => $_->ticketid,
1356                  };
1357   }
1358   (@usage);
1359 }
1360
1361 sub list_support_usage {
1362   _usage_details(\&_list_support_usage, @_);
1363 }
1364
1365 sub _list_cdr_usage {
1366   my($svc_phone, $begin, $end) = @_;
1367   map [ $_->downstream_csv('format' => 'default', 'keeparray' => 1) ], #XXX config for format
1368                        $svc_phone->get_cdrs( 'begin'=>$begin, 'end'=>$end, );
1369 }
1370
1371 sub list_cdr_usage {
1372   my $p = shift;
1373   _usage_details( \&_list_cdr_usage, $p,
1374                   'svcdb' => 'svc_phone',
1375                 );
1376 }
1377
1378 sub _usage_details {
1379   my($callback, $p, %opt) = @_;
1380
1381   my($context, $session, $custnum) = _custoragent_session_custnum($p);
1382   return { 'error' => $session } if $context eq 'error';
1383
1384   my $search = { 'svcnum' => $p->{'svcnum'} };
1385   $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
1386
1387   my $svcdb = $opt{'svcdb'} || 'svc_acct';
1388
1389   my $svc_x = qsearchs( $svcdb, $search );
1390   return { 'error' => 'No service selected in list_svc_usage' } 
1391     unless $svc_x;
1392
1393   my $header = $svcdb eq 'svc_phone'
1394                  ? [ split(',', FS::cdr::invoice_header('default') ) ]  #XXX
1395                  : [];
1396
1397   my $cust_pkg = $svc_x->cust_svc->cust_pkg;
1398   my $freq     = $cust_pkg->part_pkg->freq;
1399   my $start    = $cust_pkg->setup;
1400   #my $end      = $cust_pkg->bill; # or time?
1401   my $end      = time;
1402
1403   unless ( $p->{beginning} ) {
1404     $p->{beginning} = $cust_pkg->last_bill;
1405     $p->{ending}    = $end;
1406   }
1407
1408   my (@usage) = &$callback($svc_x, $p->{beginning}, $p->{ending});
1409
1410   #kinda false laziness with FS::cust_main::bill, but perhaps
1411   #we should really change this bit to DateTime and DateTime::Duration
1412   #
1413   #change this bit to use Date::Manip? CAREFUL with timezones (see
1414   # mailing list archive)
1415   my ($nsec,$nmin,$nhour,$nmday,$nmon,$nyear) =
1416     (localtime($p->{ending}) )[0,1,2,3,4,5];
1417   my ($psec,$pmin,$phour,$pmday,$pmon,$pyear) =
1418     (localtime($p->{beginning}) )[0,1,2,3,4,5];
1419
1420   if ( $freq =~ /^\d+$/ ) {
1421     $nmon += $freq;
1422     until ( $nmon < 12 ) { $nmon -= 12; $nyear++; }
1423     $pmon -= $freq;
1424     until ( $pmon >= 0 ) { $pmon += 12; $pyear--; }
1425   } elsif ( $freq =~ /^(\d+)w$/ ) {
1426     my $weeks = $1;
1427     $nmday += $weeks * 7;
1428     $pmday -= $weeks * 7;
1429   } elsif ( $freq =~ /^(\d+)d$/ ) {
1430     my $days = $1;
1431     $nmday += $days;
1432     $pmday -= $days;
1433   } elsif ( $freq =~ /^(\d+)h$/ ) {
1434     my $hours = $1;
1435     $nhour += $hours;
1436     $phour -= $hours;
1437   } else {
1438     return { 'error' => "unparsable frequency: ". $freq };
1439   }
1440   
1441   my $previous  = timelocal_nocheck($psec,$pmin,$phour,$pmday,$pmon,$pyear);
1442   my $next      = timelocal_nocheck($nsec,$nmin,$nhour,$nmday,$nmon,$nyear);
1443
1444   { 
1445     'error'     => '',
1446     'svcnum'    => $p->{svcnum},
1447     'beginning' => $p->{beginning},
1448     'ending'    => $p->{ending},
1449     'previous'  => ($previous > $start) ? $previous : $start,
1450     'next'      => ($next < $end) ? $next : $end,
1451     'header'    => $header,
1452     'usage'     => \@usage,
1453   };
1454 }
1455
1456 sub order_pkg {
1457   my $p = shift;
1458
1459   my($context, $session, $custnum) = _custoragent_session_custnum($p);
1460   return { 'error' => $session } if $context eq 'error';
1461
1462   my $search = { 'custnum' => $custnum };
1463   $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
1464   my $cust_main = qsearchs('cust_main', $search )
1465     or return { 'error' => "unknown custnum $custnum" };
1466
1467   my $status = $cust_main->status;
1468   #false laziness w/ClientAPI/Signup.pm
1469
1470   my $cust_pkg = new FS::cust_pkg ( {
1471     'custnum' => $custnum,
1472     'pkgpart' => $p->{'pkgpart'},
1473   } );
1474   my $error = $cust_pkg->check;
1475   return { 'error' => $error } if $error;
1476
1477   my @svc = ();
1478   unless ( $p->{'svcpart'} eq 'none' ) {
1479
1480     my $svcdb;
1481     my $svcpart = '';
1482     if ( $p->{'svcpart'} =~ /^(\d+)$/ ) {
1483       $svcpart = $1;
1484       my $part_svc = qsearchs('part_svc', { 'svcpart' => $svcpart } );
1485       return { 'error' => "Unknown svcpart $svcpart" } unless $part_svc;
1486       $svcdb = $part_svc->svcdb;
1487     } else {
1488       $svcdb = 'svc_acct';
1489     }
1490     $svcpart ||= $cust_pkg->part_pkg->svcpart($svcdb);
1491
1492     my %fields = (
1493       'svc_acct'     => [ qw( username domsvc _password sec_phrase popnum ) ],
1494       'svc_domain'   => [ qw( domain ) ],
1495       'svc_phone'    => [ qw( phonenum pin sip_password phone_name ) ],
1496       'svc_external' => [ qw( id title ) ],
1497       'svc_pbx'      => [ qw( id title ) ],
1498     );
1499   
1500     my $svc_x = "FS::$svcdb"->new( {
1501       'svcpart'   => $svcpart,
1502       map { $_ => $p->{$_} } @{$fields{$svcdb}}
1503     } );
1504     
1505     if ( $svcdb eq 'svc_acct' && exists($p->{"snarf_machine1"}) ) {
1506       my @acct_snarf;
1507       my $snarfnum = 1;
1508       while ( length($p->{"snarf_machine$snarfnum"}) ) {
1509         my $acct_snarf = new FS::acct_snarf ( {
1510           'machine'   => $p->{"snarf_machine$snarfnum"},
1511           'protocol'  => $p->{"snarf_protocol$snarfnum"},
1512           'username'  => $p->{"snarf_username$snarfnum"},
1513           '_password' => $p->{"snarf_password$snarfnum"},
1514         } );
1515         $snarfnum++;
1516         push @acct_snarf, $acct_snarf;
1517       }
1518       $svc_x->child_objects( \@acct_snarf );
1519     }
1520     
1521     my $y = $svc_x->setdefault; # arguably should be in new method
1522     return { 'error' => $y } if $y && !ref($y);
1523   
1524     $error = $svc_x->check;
1525     return { 'error' => $error } if $error;
1526
1527     push @svc, $svc_x;
1528
1529   }
1530
1531   use Tie::RefHash;
1532   tie my %hash, 'Tie::RefHash';
1533   %hash = ( $cust_pkg => \@svc );
1534   #msgcat
1535   $error = $cust_main->order_pkgs( \%hash, 'noexport' => 1 );
1536   return { 'error' => $error } if $error;
1537
1538   my $conf = new FS::Conf;
1539   if ( $conf->exists('signup_server-realtime') ) {
1540
1541     my $bill_error = _do_bop_realtime( $cust_main, $status );
1542
1543     if ($bill_error) {
1544       $cust_pkg->cancel('quiet'=>1);
1545       return $bill_error;
1546     } else {
1547       $cust_pkg->reexport;
1548     }
1549
1550   } else {
1551     $cust_pkg->reexport;
1552   }
1553
1554   my $svcnum = $svc[0] ? $svc[0]->svcnum : '';
1555
1556   return { error=>'', pkgnum=>$cust_pkg->pkgnum, svcnum=>$svcnum };
1557
1558 }
1559
1560 sub change_pkg {
1561   my $p = shift;
1562
1563   my($context, $session, $custnum) = _custoragent_session_custnum($p);
1564   return { 'error' => $session } if $context eq 'error';
1565
1566   my $search = { 'custnum' => $custnum };
1567   $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
1568   my $cust_main = qsearchs('cust_main', $search )
1569     or return { 'error' => "unknown custnum $custnum" };
1570
1571   my $status = $cust_main->status;
1572   my $cust_pkg = qsearchs('cust_pkg', { 'pkgnum' => $p->{pkgnum} } )
1573     or return { 'error' => "unknown package $p->{pkgnum}" };
1574
1575   my @newpkg;
1576   my $error = FS::cust_pkg::order( $custnum,
1577                                    [$p->{pkgpart}],
1578                                    [$p->{pkgnum}],
1579                                    \@newpkg,
1580                                  );
1581
1582   my $conf = new FS::Conf;
1583   if ( $conf->exists('signup_server-realtime') ) {
1584
1585     my $bill_error = _do_bop_realtime( $cust_main, $status );
1586
1587     if ($bill_error) {
1588       $newpkg[0]->suspend;
1589       return $bill_error;
1590     } else {
1591       $newpkg[0]->reexport;
1592     }
1593
1594   } else {  
1595     $newpkg[0]->reexport;
1596   }
1597
1598   return { error => '', pkgnum => $cust_pkg->pkgnum };
1599
1600 }
1601
1602 sub order_recharge {
1603   my $p = shift;
1604
1605   my($context, $session, $custnum) = _custoragent_session_custnum($p);
1606   return { 'error' => $session } if $context eq 'error';
1607
1608   my $search = { 'custnum' => $custnum };
1609   $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
1610   my $cust_main = qsearchs('cust_main', $search )
1611     or return { 'error' => "unknown custnum $custnum" };
1612
1613   my $status = $cust_main->status;
1614   my $cust_svc = qsearchs( 'cust_svc', { 'svcnum' => $p->{'svcnum'} } )
1615     or return { 'error' => "unknown service " . $p->{'svcnum'} };
1616
1617   my $svc_x = $cust_svc->svc_x;
1618   my $part_pkg = $cust_svc->cust_pkg->part_pkg;
1619
1620   my %vhash =
1621     map { $_ =~ /^recharge_(.*)$/; $1, $part_pkg->option($_, 1) } 
1622     qw ( recharge_seconds recharge_upbytes recharge_downbytes
1623          recharge_totalbytes );
1624   my $amount = $part_pkg->option('recharge_amount', 1); 
1625   
1626   my ($l, $v, $d) = $cust_svc->label;  # blah
1627   my $pkg = "Recharge $v"; 
1628
1629   my $bill_error = $cust_main->charge($amount, $pkg,
1630      "time: $vhash{seconds}, up: $vhash{upbytes}," . 
1631      "down: $vhash{downbytes}, total: $vhash{totalbytes}",
1632      $part_pkg->taxclass); #meh
1633
1634   my $conf = new FS::Conf;
1635   if ( $conf->exists('signup_server-realtime') && !$bill_error ) {
1636
1637     $bill_error = _do_bop_realtime( $cust_main, $status );
1638
1639     if ($bill_error) {
1640       return $bill_error;
1641     } else {
1642       my $error = $svc_x->recharge (\%vhash);
1643       return { 'error' => $error } if $error;
1644     }
1645
1646   } else {  
1647     my $error = $bill_error;
1648     $error ||= $svc_x->recharge (\%vhash);
1649     return { 'error' => $error } if $error;
1650   }
1651
1652   return { error => '', svc => $cust_svc->part_svc->svc };
1653
1654 }
1655
1656 sub _do_bop_realtime {
1657   my ($cust_main, $status) = (shift, shift);
1658
1659     my $old_balance = $cust_main->balance;
1660
1661     my $bill_error =    $cust_main->bill
1662                      || $cust_main->apply_payments_and_credits
1663                      || $cust_main->realtime_collect('selfservice' => 1);
1664
1665     if (    $cust_main->balance > $old_balance
1666          && $cust_main->balance > 0
1667          && ( $cust_main->payby !~ /^(BILL|DCRD|DCHK)$/ ?
1668               1 : $status eq 'suspended' ) ) {
1669       #this makes sense.  credit is "un-doing" the invoice
1670       my $conf = new FS::Conf;
1671       $cust_main->credit( sprintf("%.2f", $cust_main->balance - $old_balance ),
1672                           'self-service decline',
1673                           'reason_type' => $conf->config('signup_credit_type'),
1674                         );
1675       $cust_main->apply_credits( 'order' => 'newest' );
1676
1677       return { 'error' => '_decline', 'bill_error' => $bill_error };
1678     }
1679
1680     '';
1681 }
1682
1683 sub renew_info {
1684   my $p = shift;
1685
1686   my($context, $session, $custnum) = _custoragent_session_custnum($p);
1687   return { 'error' => $session } if $context eq 'error';
1688
1689   my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1690     or return { 'error' => "unknown custnum $custnum" };
1691
1692   my @cust_pkg = sort { $a->bill <=> $b->bill }
1693                  grep { $_->part_pkg->freq ne '0' }
1694                  $cust_main->ncancelled_pkgs;
1695
1696   #return { 'error' => 'No active packages to renew.' } unless @cust_pkg;
1697
1698   my $total = $cust_main->balance;
1699
1700   my @array = map {
1701                     my $bill = $_->bill;
1702                     $total += $_->part_pkg->base_recur($_, \$bill);
1703                     my $renew_date = $_->part_pkg->add_freq($_->bill);
1704                     {
1705                       'pkgnum'             => $_->pkgnum,
1706                       'amount'             => sprintf('%.2f', $total),
1707                       'bill_date'          => $_->bill,
1708                       'bill_date_pretty'   => time2str('%x', $_->bill),
1709                       'renew_date'         => $renew_date,
1710                       'renew_date_pretty'  => time2str('%x', $renew_date),
1711                       'expire_date'        => $_->expire,
1712                       'expire_date_pretty' => time2str('%x', $_->expire),
1713                     };
1714                   }
1715                   @cust_pkg;
1716
1717   return { 'dates' => \@array };
1718
1719 }
1720
1721 sub payment_info_renew_info {
1722   my $p = shift;
1723   my $renew_info   = renew_info($p);
1724   my $payment_info = payment_info($p);
1725   return { %$renew_info,
1726            %$payment_info,
1727          };
1728 }
1729
1730 sub order_renew {
1731   my $p = shift;
1732
1733   my($context, $session, $custnum) = _custoragent_session_custnum($p);
1734   return { 'error' => $session } if $context eq 'error';
1735
1736   my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1737     or return { 'error' => "unknown custnum $custnum" };
1738
1739   my $date = $p->{'date'};
1740
1741   my $now = time;
1742
1743   #freeside-daily -n -d $date fs_daily $custnum
1744   $cust_main->bill_and_collect( 'time'         => $date,
1745                                 'invoice_time' => $now,
1746                                 'actual_time'  => $now,
1747                                 'check_freq'   => '1d',
1748                               );
1749
1750   return { 'error' => '' };
1751
1752 }
1753
1754 sub suspend_pkg {
1755   my $p = shift;
1756   my $session = _cache->get($p->{'session_id'})
1757     or return { 'error' => "Can't resume session" }; #better error message
1758
1759   my $custnum = $session->{'custnum'};
1760
1761   my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1762     or return { 'error' => "unknown custnum $custnum" };
1763
1764   my $conf = new FS::Conf;
1765   my $reasonnum = 
1766     $conf->config('selfservice-self_suspend_reason', $cust_main->agentnum)
1767       or return { 'error' => 'Permission denied' };
1768
1769   my $pkgnum = $p->{'pkgnum'};
1770
1771   my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
1772                                         'pkgnum'  => $pkgnum,   } )
1773     or return { 'error' => "unknown pkgnum $pkgnum" };
1774
1775   my $error = $cust_pkg->suspend(reason => $reasonnum);
1776   return { 'error' => $error };
1777
1778 }
1779
1780 sub cancel_pkg {
1781   my $p = shift;
1782   my $session = _cache->get($p->{'session_id'})
1783     or return { 'error' => "Can't resume session" }; #better error message
1784
1785   my $custnum = $session->{'custnum'};
1786
1787   my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1788     or return { 'error' => "unknown custnum $custnum" };
1789
1790   my $pkgnum = $p->{'pkgnum'};
1791
1792   my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
1793                                         'pkgnum'  => $pkgnum,   } )
1794     or return { 'error' => "unknown pkgnum $pkgnum" };
1795
1796   my $error = $cust_pkg->cancel('quiet' => 1);
1797   return { 'error' => $error };
1798
1799 }
1800
1801 sub provision_phone {
1802  my $p = shift;
1803  my @bulkdid;
1804  @bulkdid = @{$p->{'bulkdid'}} if $p->{'bulkdid'};
1805
1806  if($p->{'svcnum'} && $p->{'svcnum'} =~ /^\d+$/){
1807       my($context, $session, $custnum) = _custoragent_session_custnum($p);
1808       return { 'error' => $session } if $context eq 'error';
1809     
1810       my $svc_phone = qsearchs('svc_phone', { svcnum => $p->{'svcnum'} });
1811       return { 'error' => 'service not found' } unless $svc_phone;
1812       return { 'error' => 'invalid svcnum' } 
1813         if $svc_phone && $svc_phone->cust_svc->cust_pkg->custnum != $custnum;
1814
1815       $svc_phone->email($p->{'email'}) 
1816         if $svc_phone->email ne $p->{'email'} && $p->{'email'} =~ /^([\w\.\d@]+|)$/;
1817       $svc_phone->forwarddst($p->{'forwarddst'}) 
1818         if $svc_phone->forwarddst ne $p->{'forwarddst'} 
1819             && $p->{'forwarddst'} =~ /^(\d+|)$/;
1820       return { 'error' => $svc_phone->replace };
1821  }
1822
1823 # single DID LNP
1824  unless($p->{'lnp'}) {
1825     $p->{'lnp_desired_due_date'} = parse_datetime($p->{'lnp_desired_due_date'});
1826     $p->{'lnp_status'} = "portingin";
1827     return _provision( 'FS::svc_phone',
1828                   [qw(lnp_desired_due_date lnp_other_provider 
1829                     lnp_other_provider_account phonenum countrycode lnp_status)],
1830                   [qw(phonenum countrycode)],
1831                   $p,
1832                   @_
1833                 );
1834  }
1835
1836 # single DID order
1837  unless (scalar(@bulkdid)) {
1838     return _provision( 'FS::svc_phone',
1839                   [qw(phonenum countrycode)],
1840                   [qw(phonenum countrycode)],
1841                   $p,
1842                   @_
1843                 );
1844  }
1845
1846 # bulk DID order case
1847   my $error;
1848   foreach my $did ( @bulkdid ) {
1849     $did =~ s/[^0-9]//g;
1850     $error = _provision( 'FS::svc_phone',
1851               [qw(phonenum countrycode)],
1852               [qw(phonenum countrycode)],
1853               {
1854                 'pkgnum' => $p->{'pkgnum'},
1855                 'svcpart' => $p->{'svcpart'},
1856                 'phonenum' => $did,
1857                 'countrycode' => $p->{'countrycode'},
1858                 'session_id' => $p->{'session_id'},
1859               }
1860             );
1861     return $error if ($error->{'error'} && length($error->{'error'}) > 1);
1862   }
1863   { 'bulkdid' => [ @bulkdid ], 'svc' => $error->{'svc'} }
1864 }
1865
1866 sub provision_acct {
1867   my $p = shift;
1868   warn "provision_acct called\n"
1869     if $DEBUG;
1870
1871   return { 'error' => gettext('passwords_dont_match') }
1872     if $p->{'_password'} ne $p->{'_password2'};
1873   return { 'error' => gettext('empty_password') }
1874     unless length($p->{'_password'});
1875  
1876   if ($p->{'domsvc'}) {
1877     my %domains = domain_select_hash FS::svc_acct(map { $_ => $p->{$_} }
1878                                                   qw ( svcpart pkgnum ) );
1879     return { 'error' => gettext('invalid_domain') }
1880       unless ($domains{$p->{'domsvc'}});
1881   }
1882
1883   warn "provision_acct calling _provision\n"
1884     if $DEBUG;
1885   _provision( 'FS::svc_acct',
1886               [qw(username _password domsvc)],
1887               [qw(username _password domsvc)],
1888               $p,
1889               @_
1890             );
1891 }
1892
1893 sub provision_external {
1894   my $p = shift;
1895   #_provision( 'FS::svc_external', [qw(id title)], [qw(id title)], $p, @_ );
1896   _provision( 'FS::svc_external',
1897               [],
1898               [qw(id title)],
1899               $p,
1900               @_
1901             );
1902 }
1903
1904 sub _provision {
1905   my( $class, $fields, $return_fields, $p ) = splice(@_, 0, 4);
1906   warn "_provision called for $class\n"
1907     if $DEBUG;
1908
1909   my($context, $session, $custnum) = _custoragent_session_custnum($p);
1910   return { 'error' => $session } if $context eq 'error';
1911
1912   my $search = { 'custnum' => $custnum };
1913   $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
1914   my $cust_main = qsearchs('cust_main', $search )
1915     or return { 'error' => "unknown custnum $custnum" };
1916
1917   my $pkgnum = $p->{'pkgnum'};
1918
1919   warn "searching for custnum $custnum pkgnum $pkgnum\n"
1920     if $DEBUG;
1921   my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
1922                                         'pkgnum'  => $pkgnum,
1923                                                                } )
1924     or return { 'error' => "unknown pkgnum $pkgnum" };
1925
1926   warn "searching for svcpart ". $p->{'svcpart'}. "\n"
1927     if $DEBUG;
1928   my $part_svc = qsearchs('part_svc', { 'svcpart' => $p->{'svcpart'} } )
1929     or return { 'error' => "unknown svcpart $p->{'svcpart'}" };
1930
1931   warn "creating $class record\n"
1932     if $DEBUG;
1933   my $svc_x = $class->new( {
1934     'pkgnum'  => $p->{'pkgnum'},
1935     'svcpart' => $p->{'svcpart'},
1936     map { $_ => $p->{$_} } @$fields
1937   } );
1938   warn "inserting $class record\n"
1939     if $DEBUG;
1940   my $error = $svc_x->insert;
1941
1942   unless ( $error ) {
1943     warn "finding inserted record for svcnum ". $svc_x->svcnum. "\n"
1944       if $DEBUG;
1945     $svc_x = qsearchs($svc_x->table, { 'svcnum' => $svc_x->svcnum })
1946   }
1947
1948   my $return = { 'svc'   => $part_svc->svc,
1949                  'error' => $error,
1950                  map { $_ => $svc_x->get($_) } @$return_fields
1951                };
1952   warn "_provision returning ". Dumper($return). "\n"
1953     if $DEBUG;
1954   return $return;
1955
1956 }
1957
1958 sub part_svc_info {
1959   my $p = shift;
1960
1961   my($context, $session, $custnum) = _custoragent_session_custnum($p);
1962   return { 'error' => $session } if $context eq 'error';
1963
1964   my $search = { 'custnum' => $custnum };
1965   $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
1966   my $cust_main = qsearchs('cust_main', $search )
1967     or return { 'error' => "unknown custnum $custnum" };
1968
1969   my $pkgnum = $p->{'pkgnum'};
1970
1971   my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
1972                                         'pkgnum'  => $pkgnum,
1973                                                                } )
1974     or return { 'error' => "unknown pkgnum $pkgnum" };
1975
1976   my $svcpart = $p->{'svcpart'};
1977
1978   my $pkg_svc = qsearchs('pkg_svc', { 'pkgpart' => $cust_pkg->pkgpart,
1979                                       'svcpart' => $svcpart,           } )
1980     or return { 'error' => "unknown svcpart $svcpart for pkgnum $pkgnum" };
1981   my $part_svc = $pkg_svc->part_svc;
1982
1983   my $conf = new FS::Conf;
1984
1985   my $ret = {
1986     'svc'     => $part_svc->svc,
1987     'svcdb'   => $part_svc->svcdb,
1988     'pkgnum'  => $pkgnum,
1989     'svcpart' => $svcpart,
1990     'custnum' => $custnum,
1991
1992     'security_phrase' => 0, #XXX !
1993     'svc_acct_pop'    => [], #XXX !
1994     'popnum'          => '',
1995     'init_popstate'   => '',
1996     'popac'           => '',
1997     'acstate'         => '',
1998
1999     'small_custview' =>
2000       small_custview( $cust_main, $conf->config('countrydefault') ),
2001
2002   };
2003
2004   if ($p->{'svcnum'} && $p->{'svcnum'} =~ /^\d+$/ 
2005                      && $ret->{'svcdb'} eq 'svc_phone') {
2006         $ret->{'svcnum'} = $p->{'svcnum'};
2007         my $svc_phone = qsearchs('svc_phone', { svcnum => $p->{'svcnum'} });
2008         if ( $svc_phone && $svc_phone->cust_svc->cust_pkg->custnum == $custnum ) {
2009             $ret->{'email'} = $svc_phone->email;
2010             $ret->{'forwarddst'} = $svc_phone->forwarddst;
2011         }
2012   }
2013
2014   $ret;
2015 }
2016
2017 sub unprovision_svc {
2018   my $p = shift;
2019
2020   my($context, $session, $custnum) = _custoragent_session_custnum($p);
2021   return { 'error' => $session } if $context eq 'error';
2022
2023   my $search = { 'custnum' => $custnum };
2024   $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2025   my $cust_main = qsearchs('cust_main', $search )
2026     or return { 'error' => "unknown custnum $custnum" };
2027
2028   my $svcnum = $p->{'svcnum'};
2029
2030   my $cust_svc = qsearchs('cust_svc', { 'svcnum'  => $svcnum, } )
2031     or return { 'error' => "unknown svcnum $svcnum" };
2032
2033   return { 'error' => "Service $svcnum does not belong to customer $custnum" }
2034     unless $cust_svc->cust_pkg->custnum == $custnum;
2035
2036   my $conf = new FS::Conf;
2037
2038   return { 'svc'   => $cust_svc->part_svc->svc,
2039            'error' => $cust_svc->cancel,
2040            'small_custview' =>
2041              small_custview( $cust_main, $conf->config('countrydefault') ),
2042          };
2043
2044 }
2045
2046 sub myaccount_passwd {
2047   my $p = shift;
2048   my($context, $session, $custnum) = _custoragent_session_custnum($p);
2049   return { 'error' => $session } if $context eq 'error';
2050
2051   return { 'error' => "New passwords don't match." }
2052     if $p->{'new_password'} ne $p->{'new_password2'};
2053
2054   return { 'error' => 'Enter new password' }
2055     unless length($p->{'new_password'});
2056
2057   #my $search = { 'custnum' => $custnum };
2058   #$search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2059   $custnum =~ /^(\d+)$/ or die "illegal custnum";
2060   my $search = " AND custnum = $1";
2061   $search .= " AND agentnum = ". $session->{'agentnum'} if $context eq 'agent';
2062
2063   my $svc_acct = qsearchs( {
2064     'table'     => 'svc_acct',
2065     'addl_from' => 'LEFT JOIN cust_svc  USING ( svcnum  ) '.
2066                    'LEFT JOIN cust_pkg  USING ( pkgnum  ) '.
2067                    'LEFT JOIN cust_main USING ( custnum ) ',
2068     'hashref'   => { 'svcnum' => $p->{'svcnum'}, },
2069     'extra_sql' => $search, #important
2070   } )
2071     or return { 'error' => "Service not found" };
2072
2073   $svc_acct->_password($p->{'new_password'});
2074   my $error = $svc_acct->replace();
2075
2076   my($label, $value) = $svc_acct->cust_svc->label;
2077
2078   return { 'error' => $error,
2079            'label' => $label,
2080            'value' => $value,
2081          };
2082
2083 }
2084
2085 sub create_ticket {
2086   my $p = shift;
2087   my($context, $session, $custnum) = _custoragent_session_custnum($p);
2088   return { 'error' => $session } if $context eq 'error';
2089
2090   warn "$me create_ticket: initializing ticket system\n" if $DEBUG;
2091   FS::TicketSystem->init();
2092
2093   my $conf = new FS::Conf;
2094   my $queue = $p->{'queue'}
2095               || $conf->config('ticket_system-selfservice_queueid')
2096               || $conf->config('ticket_system-default_queueid');
2097
2098   warn "$me create_ticket: creating ticket\n" if $DEBUG;
2099   my $err_or_ticket = FS::TicketSystem->create_ticket(
2100     '', #create RT session based on FS CurrentUser (fs_selfservice)
2101     'queue'   => $queue,
2102     'custnum' => $custnum,
2103     'svcnum'  => $session->{'svcnum'},
2104     map { $_ => $p->{$_} } qw( requestor cc subject message mime_type )
2105   );
2106
2107   if ( ref($err_or_ticket) ) {
2108     warn "$me create_ticket: successful: ". $err_or_ticket->id. "\n"
2109       if $DEBUG;
2110     return { 'error'     => '',
2111              'ticket_id' => $err_or_ticket->id,
2112            };
2113   } else {
2114     warn "$me create_ticket: unsuccessful: $err_or_ticket\n"
2115       if $DEBUG;
2116     return { 'error' => $err_or_ticket };
2117   }
2118
2119
2120 }
2121
2122 sub did_report {
2123   my $p = shift;
2124   my($context, $session, $custnum) = _custoragent_session_custnum($p);
2125   return { 'error' => $session } if $context eq 'error';
2126  
2127   return { error => 'requested format not implemented' } 
2128     unless ($p->{'format'} eq 'csv' || $p->{'format'} eq 'xls');
2129
2130   my $conf = new FS::Conf;
2131   my $age_threshold = 0;
2132   $age_threshold = time() - $conf->config('selfservice-recent-did-age')
2133     if ($p->{'recentonly'} && $conf->exists('selfservice-recent-did-age'));
2134
2135   my $search = { 'custnum' => $custnum };
2136   $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2137   my $cust_main = qsearchs('cust_main', $search )
2138     or return { 'error' => "unknown custnum $custnum" };
2139
2140 # does it make more sense to just run one sql query for this instead of all the
2141 # insanity below? would increase performance greately for large data sets?
2142   my @svc_phone = ();
2143   foreach my $cust_pkg ( $cust_main->ncancelled_pkgs ) {
2144         my @part_svc = $cust_pkg->part_svc;
2145         foreach my $part_svc ( @part_svc ) {
2146             if($part_svc->svcdb eq 'svc_phone'){
2147                 my @cust_pkg_svc = @{$part_svc->cust_pkg_svc};
2148                 foreach my $cust_pkg_svc ( @cust_pkg_svc ) {
2149                     push @svc_phone, $cust_pkg_svc->svc_x
2150                         if $cust_pkg_svc->date_inserted >= $age_threshold;
2151                 }
2152             }
2153         }
2154   }
2155
2156   my $csv;
2157   my $xls;
2158   my($xls_r,$xls_c) = (0,0);
2159   my $xls_workbook;
2160   my $content = '';
2161   my @fields = qw( countrycode phonenum pin sip_password phone_name );
2162   if($p->{'format'} eq 'csv') {
2163     $csv = new Text::CSV_XS { 'always_quote' => 1,
2164                                  'eol'          => "\n",
2165                                 };
2166     return { 'error' => 'Unable to create CSV' } unless $csv->combine(@fields);
2167     $content .= $csv->string;
2168   }
2169   elsif($p->{'format'} eq 'xls') {
2170     my $XLS1 = new IO::Scalar \$content;
2171     $xls_workbook = Spreadsheet::WriteExcel->new($XLS1) 
2172         or return { 'error' => "Error opening .xls file: $!" };
2173     $xls = $xls_workbook->add_worksheet('DIDs');
2174     foreach ( @fields ) {
2175         $xls->write(0,$xls_c++,$_);
2176     }
2177     $xls_r++;
2178   }
2179
2180   foreach my $svc_phone ( @svc_phone ) {
2181     my @cols = map { $svc_phone->$_ } @fields;
2182     if($p->{'format'} eq 'csv') {
2183         return { 'error' => 'Unable to create CSV' } 
2184             unless $csv->combine(@cols);
2185         $content .= $csv->string;
2186     }
2187     elsif($p->{'format'} eq 'xls') {
2188         $xls_c = 0;
2189         foreach ( @cols ) {
2190             $xls->write($xls_r,$xls_c++,$_);
2191         }
2192         $xls_r++;
2193     }
2194   }
2195
2196   $xls_workbook->close() if $p->{'format'} eq 'xls';
2197   
2198   { content => $content, format => $p->{'format'}, };
2199 }
2200
2201 sub get_ticket {
2202   my $p = shift;
2203   my($context, $session, $custnum) = _custoragent_session_custnum($p);
2204   return { 'error' => $session } if $context eq 'error';
2205
2206   warn "$me get_ticket: initializing ticket system\n" if $DEBUG;
2207   FS::TicketSystem->init();
2208   return { 'error' => 'get_ticket configuration error' }
2209     if $FS::TicketSystem::system ne 'RT_Internal';
2210
2211   # check existence and ownership as part of this
2212   warn "$me get_ticket: fetching ticket\n" if $DEBUG;
2213   my $rt_session = FS::TicketSystem->session('');
2214   my $Ticket = FS::TicketSystem->get_ticket_object(
2215     $rt_session, 
2216     ticket_id => $p->{'ticket_id'},
2217     custnum => $custnum
2218   );
2219   return { 'error' => 'ticket not found' } if !$Ticket;
2220
2221   if ( length( $p->{'subject'} || '' ) ) {
2222     # subject change
2223     if ( $p->{'subject'} ne $Ticket->Subject ) {
2224       my ($val, $msg) = $Ticket->SetSubject($p->{'subject'});
2225       return { 'error' => "unable to set subject: $msg" } if !$val;
2226     }
2227   }
2228
2229   if(length($p->{'reply'})) {
2230     my @err_or_res = FS::TicketSystem->correspond_ticket(
2231       $rt_session,
2232       'ticket_id' => $p->{'ticket_id'},
2233       'content' => $p->{'reply'},
2234     );
2235
2236     return { 'error' => 'unable to reply to ticket' } 
2237     unless ( $err_or_res[0] != 0 && defined $err_or_res[2] );
2238   }
2239
2240   warn "$me get_ticket: getting ticket history\n" if $DEBUG;
2241   my $err_or_ticket = FS::TicketSystem->get_ticket(
2242     $rt_session,
2243     'ticket_id' => $p->{'ticket_id'},
2244   );
2245
2246   if ( !ref($err_or_ticket) ) { # there is no way this should ever happen
2247     warn "$me get_ticket: unsuccessful: $err_or_ticket\n"
2248       if $DEBUG;
2249     return { 'error' => $err_or_ticket };
2250   }
2251
2252   my @custs = @{$err_or_ticket->{'custs'}};
2253   my @txns = @{$err_or_ticket->{'txns'}};
2254   my @filtered_txns;
2255
2256   # superseded by check in get_ticket_object
2257   #return { 'error' => 'invalid ticket requested' } 
2258   #unless grep($_ eq $custnum, @custs);
2259
2260   foreach my $txn ( @txns ) {
2261     push @filtered_txns, $txn 
2262     if ($txn->{'type'} eq 'EmailRecord' 
2263       || $txn->{'type'} eq 'Correspond'
2264       || $txn->{'type'} eq 'Create');
2265   }
2266
2267   warn "$me get_ticket: successful: \n"
2268   if $DEBUG;
2269   return { 'error'     => '',
2270     'transactions' => \@filtered_txns,
2271     'ticket_fields' => $err_or_ticket->{'fields'},
2272     'ticket_id' => $p->{'ticket_id'},
2273   };
2274 }
2275
2276 sub adjust_ticket_priority {
2277   my $p = shift;
2278   my($context, $session, $custnum) = _custoragent_session_custnum($p);
2279   return { 'error' => $session } if $context eq 'error';
2280
2281   warn "$me adjust_ticket_priority: initializing ticket system\n" if $DEBUG;
2282   FS::TicketSystem->init;
2283   my $ss_priority = FS::TicketSystem->selfservice_priority;
2284
2285   return { 'error' => 'adjust_ticket_priority configuration error' }
2286     if $FS::TicketSystem::system ne 'RT_Internal'
2287       or !$ss_priority;
2288
2289   my $values = $p->{'values'}; #hashref, id => priority value
2290   my %ticket_error;
2291
2292   foreach my $id (keys %$values) {
2293     warn "$me adjust_ticket_priority: fetching ticket $id\n" if $DEBUG;
2294     my $Ticket = FS::TicketSystem->get_ticket_object('',
2295       'ticket_id' => $id,
2296       'custnum'   => $custnum,
2297     );
2298     if ( !$Ticket ) {
2299       $ticket_error{$id} = 'ticket not found';
2300       next;
2301     }
2302     
2303   # RT API stuff--would we gain anything by wrapping this in FS::TicketSystem?
2304   # We're not going to implement it for RT_External.
2305     my $old_value = $Ticket->FirstCustomFieldValue($ss_priority);
2306     my $new_value = $values->{$id};
2307     next if $old_value eq $new_value;
2308
2309     warn "$me adjust_ticket_priority: updating ticket $id\n" if $DEBUG;
2310
2311     # AddCustomFieldValue works fine (replacing any existing value) if it's 
2312     # a single-valued custom field, which it should be.  If it's not, you're 
2313     # doing something wrong.
2314     my ($val, $msg);
2315     if ( length($new_value) ) {
2316       ($val, $msg) = $Ticket->AddCustomFieldValue( 
2317         Field => $ss_priority,
2318         Value => $new_value,
2319       );
2320     }
2321     else {
2322       ($val, $msg) = $Ticket->DeleteCustomFieldValue(
2323         Field => $ss_priority,
2324         Value => $old_value,
2325       );
2326     }
2327
2328     $ticket_error{$id} = $msg if !$val;
2329     warn "$me adjust_ticket_priority: $id: $msg\n" if $DEBUG and !$val;
2330   }
2331   return { 'error' => '',
2332            'ticket_error' => \%ticket_error,
2333            %{ customer_info($p) } # send updated customer info back
2334          }
2335 }
2336
2337 #--
2338
2339 sub _custoragent_session_custnum {
2340   my $p = shift;
2341
2342   my($context, $session, $custnum);
2343   if ( $p->{'session_id'} ) {
2344
2345     $context = 'customer';
2346     $session = _cache->get($p->{'session_id'})
2347       or return ( 'error' => "Can't resume session" ); #better error message
2348     $custnum = $session->{'custnum'};
2349
2350   } elsif ( $p->{'agent_session_id'} ) {
2351
2352     $context = 'agent';
2353     my $agent_cache = new FS::ClientAPI_SessionCache( {
2354       'namespace' => 'FS::ClientAPI::Agent',
2355     } );
2356     $session = $agent_cache->get($p->{'agent_session_id'})
2357       or return ( 'error' => "Can't resume session" ); #better error message
2358     $custnum = $p->{'custnum'};
2359
2360   } else {
2361     $context = 'error';
2362     return ( 'error' => "Can't resume session" ); #better error message
2363   }
2364
2365   ($context, $session, $custnum);
2366
2367 }
2368
2369 1;
2370