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