71513: Card tokenization [v3 backport]
[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 IO::Scalar;
8 use Data::Dumper;
9 use Digest::MD5 qw(md5_hex);
10 use Digest::SHA qw(sha512_hex);
11 use Date::Format;
12 use Time::Duration;
13 use Time::Local qw(timelocal_nocheck);
14 use Business::CreditCard 0.35;
15 use HTML::Entities;
16 use Text::CSV_XS;
17 use Spreadsheet::WriteExcel;
18 use OLE::Storage_Lite;
19 use FS::UI::Web::small_custview qw(small_custview); #less doh
20 use FS::UI::Web;
21 use FS::UI::bytecount qw( display_bytecount );
22 use FS::Conf;
23 #use FS::UID qw(dbh);
24 use FS::Record qw(qsearch qsearchs dbh);
25 use FS::Msgcat qw(gettext);
26 use FS::Misc qw(card_types money_pretty);
27 use FS::Misc::DateTime qw(parse_datetime);
28 use FS::TicketSystem;
29 use FS::ClientAPI_SessionCache;
30 use FS::cust_svc;
31 use FS::svc_acct;
32 use FS::svc_forward;
33 use FS::svc_domain;
34 use FS::svc_phone;
35 use FS::svc_external;
36 use FS::svc_dsl;
37 use FS::dsl_device;
38 use FS::part_svc;
39 use FS::cust_main;
40 use FS::cust_bill;
41 use FS::legacy_cust_bill;
42 use FS::cust_main_county;
43 use FS::part_pkg;
44 use FS::cust_pkg;
45 use FS::payby;
46 use FS::acct_rt_transaction;
47 use FS::msg_template;
48 use FS::contact;
49 use FS::cust_location;
50
51 # for code organization
52 use FS::ClientAPI::MyAccount::contact;
53 use FS::ClientAPI::MyAccount::quotation;
54
55 $DEBUG = 0;
56 $me = '[FS::ClientAPI::MyAccount]';
57
58 use vars qw( @cust_main_editable_fields @location_editable_fields );
59 @cust_main_editable_fields = qw(
60   first last company daytime night fax mobile
61   locale
62   payby payinfo payname paystart_month paystart_year payissue payip
63   ss paytype paystate stateid stateid_state
64 );
65 @location_editable_fields = qw(
66   address1 address2 city county state zip country
67 );
68
69
70 BEGIN { #preload to reduce time customer_info takes
71   if ( $FS::TicketSystem::system ) {
72     warn "$me: initializing ticket system\n" if $DEBUG;
73     FS::TicketSystem->init();
74   }
75 }
76
77 sub _cache {
78   $cache ||= new FS::ClientAPI_SessionCache( {
79                'namespace' => 'FS::ClientAPI::MyAccount',
80              } );
81 }
82
83 sub skin_info {
84   my $p = shift;
85
86   my($context, $session, $custnum) = _custoragent_session_custnum($p);
87   #return { 'error' => $session } if $context eq 'error';
88
89   my $agentnum = '';
90   if ( $context eq 'customer' ) {
91
92     my $sth = dbh->prepare('SELECT agentnum FROM cust_main WHERE custnum = ?')
93       or die dbh->errstr;
94
95     $sth->execute($custnum) or die $sth->errstr;
96
97     $agentnum = $sth->fetchrow_arrayref->[0]
98       or die "no agentnum for custnum $custnum";
99
100   #} elsif ( $context eq 'agent' ) {
101   } elsif ( defined($p->{'agentnum'}) and $p->{'agentnum'} =~ /^(\d+)$/ ) {
102     $agentnum = $1;
103   }
104   $p->{'agentnum'} = $agentnum;
105
106   my $conf = new FS::Conf;
107
108   #false laziness w/Signup.pm
109
110   my $skin_info_cache_agent = _cache->get("skin_info_cache_agent$agentnum");
111
112   if ( $skin_info_cache_agent ) {
113
114     warn "$me loading cached skin info for agentnum $agentnum\n"
115       if $DEBUG > 1;
116
117   } else {
118
119     warn "$me populating skin info cache for agentnum $agentnum\n"
120       if $DEBUG > 1;
121
122     $skin_info_cache_agent = {
123       'agentnum' => $agentnum,
124       ( map { $_ => scalar( $conf->config($_, $agentnum) ) }
125         qw( company_name date_format ) ),
126       ( map { $_ => scalar( $conf->config("selfservice-$_", $agentnum ) ) }
127         qw( body_bgcolor box_bgcolor stripe1_bgcolor stripe2_bgcolor
128             text_color link_color vlink_color hlink_color alink_color
129             font title_color title_align title_size menu_bgcolor menu_fontsize
130           )
131       ),
132       'menu_disable' => [ $conf->config('selfservice-menu_disable',$agentnum) ],
133       ( map { $_ => $conf->exists("selfservice-$_", $agentnum ) }
134         qw( menu_skipblanks menu_skipheadings menu_nounderline no_logo enable_payment_without_balance )
135       ),
136       ( map { $_ => scalar($conf->config_binary("selfservice-$_", $agentnum)) }
137         qw( title_left_image title_right_image
138             menu_top_image menu_body_image menu_bottom_image
139           )
140       ),
141       'logo' => scalar($conf->config_binary('logo.png', $agentnum )),
142       ( map { $_ => join("\n", $conf->config("selfservice-$_", $agentnum ) ) }
143         qw( head body_header body_footer company_address ) ),
144       'money_char' => $conf->config("money_char") || '$',
145       'menu' => join("\n", $conf->config("ng_selfservice-menu", $agentnum ) ) ||
146                 'main.php Home
147
148                  services.php Services
149                  services.php My Services
150                  services_new.php Order a new service
151
152                  personal.php Profile
153                  personal.php Personal Information
154                  password.php Change Password
155
156                  payment.php Payments
157                  payment_cc.php Credit Card Payment
158                  payment_ach.php Electronic Check Payment
159                  payment_paypal.php PayPal Payment
160                  payment_webpay.php Webpay Payments
161
162                  usage.php Usage
163                  usage_data.php Data usage
164                  usage_cdr.php Call usage
165
166                  tickets.php Help Desk
167                  tickets.php Open Tickets
168                  tickets_resolved.php Resolved Tickets
169                  ticket_create.php Create a new ticket
170
171                  docs.php FAQs
172
173                  logout.php Logout
174                 ',
175     };
176
177     _cache->set("skin_info_cache_agent$agentnum", $skin_info_cache_agent);
178
179   }
180
181   #{ %$skin_info_cache_agent };
182   $skin_info_cache_agent;
183
184 }
185
186 sub login_info {
187   my $p = shift;
188
189   my $conf = new FS::Conf;
190
191   my %info = (
192     %{ skin_info($p) },
193     'phone_login'  => $conf->exists('selfservice_server-phone_login'),
194     'single_domain'=> scalar($conf->config('selfservice_server-single_domain')),
195     'banner_url'       => scalar($conf->config('selfservice-login_banner_url')),
196     'banner_image_md5' => 
197       md5_hex($conf->config_binary('selfservice-login_banner_image')),
198   );
199
200   return \%info;
201
202 }
203
204 sub login_banner_image {
205   my $p = shift;
206   my $conf = new FS::Conf;
207   my $image = $conf->config_binary('selfservice-login_banner_image');
208   return { 
209     'md5'   => md5_hex($image),
210     'image' => $image,
211   };
212 }
213
214 #false laziness w/FS::ClientAPI::passwd::passwd
215 sub login {
216   my $p = shift;
217
218   my $conf = new FS::Conf;
219
220   my $svc_x = '';
221   my $session = {};
222   if ( $p->{'domain'} eq 'svc_phone'
223        && $conf->exists('selfservice_server-phone_login') ) { 
224
225     my $svc_phone = qsearchs( 'svc_phone', { 'phonenum' => $p->{'username'} } );
226     return { error => 'Number not found.' } unless $svc_phone;
227
228     #XXX?
229     #my $pkg_svc = $svc_acct->cust_svc->pkg_svc;
230     #return { error => 'Only primary user may log in.' } 
231     #  if $conf->exists('selfservice_server-primary_only')
232     #    && ( ! $pkg_svc || $pkg_svc->primary_svc ne 'Y' );
233
234     return { error => 'Incorrect PIN.' }
235       unless $svc_phone->check_pin($p->{'password'});
236
237     $svc_x = $svc_phone;
238
239   } elsif ( $p->{email}
240               && (my $contact = FS::contact->by_selfservice_email($p->{email}))
241           )
242   {
243     return { error => 'Incorrect contact password.' }
244       unless $contact->authenticate_password($p->{'password'});
245
246     $session->{'contactnum'} = $contact->contactnum;
247
248     $session->{'custnum'} = $contact->custnum;
249
250   } else {
251
252     ( $p->{username}, $p->{domain} ) = split('@', $p->{email}) if $p->{email};
253
254     my $svc_domain = qsearchs('svc_domain', { 'domain' => $p->{'domain'} } )
255       or return { error => 'Domain '. $p->{'domain'}. ' not found' };
256
257     my @svc_acct = qsearch( 'svc_acct', { 'username'  => $p->{'username'},
258                                           'domsvc'    => $svc_domain->svcnum, }
259                           );
260
261     if ( $conf->exists('selfservice_server-login_svcpart') ) {
262       my @svcpart = $conf->config('selfservice_server-login_svcpart');
263       @svc_acct = grep { my $svcpart = $_->cust_svc->svcpart;
264                          scalar( grep( $_ eq $svcpart, @svcpart ) );
265                        }
266                     @svc_acct;
267     }
268
269     if ( $conf->exists('selfservice_server-primary_only') ) {
270         @svc_acct =
271           grep {
272             my $cust_svc = $_->cust_svc;
273             $cust_svc->cust_pkg->part_pkg->svcpart([qw( svc_acct svc_phone )])
274               == $cust_svc->svcpart
275           }
276           @svc_acct;
277     }
278
279     return { error => 'User not found.' } unless @svc_acct;
280
281     #return { error => 'Multiple users.' } if scalar(@svc_acct) > 1;
282
283     my $svc_acct = $svc_acct[0];
284
285     if ( $conf->exists('selfservice_server-login_svcpart') ) {
286       my @svcpart = $conf->config('selfservice_server-login_svcpart');
287       my $svcpart = $svc_acct->cust_svc->svcpart;
288       return { error => 'Invalid user.' } 
289         unless grep($_ eq $svcpart, @svcpart);
290     }
291
292     return { error => 'Incorrect password.' }
293       unless $svc_acct->check_password($p->{'password'});
294
295     $svc_x = $svc_acct;
296
297   }
298
299   if ( $svc_x ) {
300
301     $session->{'svcnum'} = $svc_x->svcnum;
302
303     my $cust_svc = $svc_x->cust_svc;
304     my $cust_pkg = $cust_svc->cust_pkg;
305     if ( $cust_pkg ) {
306       my $cust_main = $cust_pkg->cust_main;
307       $session->{'custnum'} = $cust_main->custnum;
308       if ( $conf->exists('pkg-balances') ) {
309         my @cust_pkg = grep { $_->part_pkg->freq !~ /^(0|$)/ }
310                             $cust_main->ncancelled_pkgs;
311         $session->{'pkgnum'} = $cust_pkg->pkgnum
312           if scalar(@cust_pkg) > 1;
313       }
314     }
315
316     #my $pkg_svc = $svc_acct->cust_svc->pkg_svc;
317     #return { error => 'Only primary user may log in.' } 
318     #  if $conf->exists('selfservice_server-primary_only')
319     #    && ( ! $pkg_svc || $pkg_svc->primary_svc ne 'Y' );
320     my $part_pkg = $cust_pkg->part_pkg;
321     return { error => 'Only primary user may log in.' }
322       if $conf->exists('selfservice_server-primary_only')
323          && $cust_svc->svcpart != $part_pkg->svcpart([qw( svc_acct svc_phone )]);
324
325   }
326
327   my $session_id;
328   do {
329     $session_id = md5_hex(md5_hex(time(). {}. rand(). $$))
330   } until ( ! defined _cache->get($session_id) ); #just in case
331
332   my $timeout = $conf->config('selfservice-session_timeout') || '1 hour';
333   _cache->set( $session_id, $session, $timeout );
334
335   return { 'error'      => '',
336            'session_id' => $session_id,
337          };
338 }
339
340 sub logout {
341   my $p = shift;
342   my $skin_info = skin_info($p);
343   if ( $p->{'session_id'} ) {
344     _cache->remove($p->{'session_id'});
345     return { %$skin_info, 'error' => '' };
346   } else {
347     return { %$skin_info, 'error' => "Can't resume session" }; #better error message
348   }
349 }
350
351 sub switch_acct {
352   my $p = shift;
353
354   my($context, $session, $custnum) = _custoragent_session_custnum($p);
355   return { 'error' => $session } if $context eq 'error';
356
357   my $svc_acct = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_acct' )
358     or return { 'error' => "Service not found" };
359
360   $session->{'svcnum'} = $svc_acct->svcnum;
361
362   my $conf = new FS::Conf;
363   my $timeout = $conf->config('selfservice-session_timeout') || '1 hour';
364   _cache->set( $p->{'session_id'}, $session, $timeout );
365
366   return { 'error' => '' };
367
368 }
369
370 sub payment_gateway {
371   # internal use only
372   # takes a cust_main and a cust_payby entry, returns the payment_gateway
373   my $conf = new FS::Conf;
374   my $cust_main = shift;
375   my $cust_payby = shift;
376   return '' if ! FS::payby->realtime($cust_payby);
377   my $pg = $cust_main->agent->payment_gateway(
378     'method'  => FS::payby->payby2bop($cust_payby),
379     'nofatal' => 1
380   );
381   return $pg;
382 }
383
384 sub access_info {
385   my $p = shift;
386
387   my $conf = new FS::Conf;
388
389   my $info = skin_info($p);
390
391   use vars qw( $cust_paybys ); #cache for performance
392   unless ( $cust_paybys ) {
393
394     my %cust_paybys = map { $_ => 1 }
395                       map { FS::payby->payby2payment($_) }
396                           $conf->config('signup_server-payby');
397
398     $cust_paybys = [ keys %cust_paybys ];
399
400   }
401   $info->{'cust_paybys'} = $cust_paybys;
402
403   my($context, $session, $custnum) = _custoragent_session_custnum($p);
404   return { 'error' => $session } if $context eq 'error';
405
406   my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
407     or return { 'error' => "unknown custnum $custnum" };
408
409   $info->{'hide_payment_fields'} = [ 
410     map { 
411       my $pg = payment_gateway($cust_main, $_);
412       $pg && $pg->gateway_namespace eq 'Business::OnlineThirdPartyPayment';
413     } @{ $info->{cust_paybys} }
414   ];
415
416   $info->{'self_suspend_reason'} = 
417       $conf->config('selfservice-self_suspend_reason', $cust_main->agentnum);
418
419   $info->{'edit_ticket_subject'} =
420       $conf->exists('ticket_system-selfservice_edit_subject') && 
421       $cust_main->edit_subject;
422
423   $info->{'timeout'} = $conf->config('selfservice-timeout') || 3600;
424
425   $info->{'hide_usage'} = $conf->exists('selfservice_hide-usage');
426
427   return { %$info,
428            'custnum'       => $custnum,
429            'access_pkgnum' => $session->{'pkgnum'},
430            'access_svcnum' => $session->{'svcnum'},
431          };
432 }
433
434 sub customer_info {
435   my $p = shift;
436
437   my($context, $session, $custnum) = _custoragent_session_custnum($p);
438   return { 'error' => $session } if $context eq 'error';
439
440   my %return;
441
442   my $conf = new FS::Conf;
443   $return{'require_address2'} = $conf->exists('cust_main-require_address2');
444
445 #  if ( $FS::TicketSystem::system ) {
446 #    warn "$me customer_info: initializing ticket system\n" if $DEBUG;
447 #    FS::TicketSystem->init();
448 #  }
449  
450   if ( $custnum ) { #customer record
451
452     %return = ( %return, %{ customer_info_short($p) } );
453
454     #redundant with customer_info_short, but we need it for several things below
455     my $search = { 'custnum' => $custnum };
456     $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
457     my $cust_main = qsearchs('cust_main', $search )
458       or return { 'error' => "unknown custnum $custnum" };
459
460     my $list_tickets = list_tickets($p);
461     $return{'tickets'} = $list_tickets->{'tickets'};
462
463     if ( $session->{'pkgnum'} ) {
464       #XXX open invoices in the pkg-balances case
465     } else {
466       $return{'money_char'} = $conf->config("money_char") || '$';
467       my @open = map {
468                        {
469                          invnum     => $_->invnum,
470                          date       => time2str("%b %o, %Y", $_->_date),
471                          owed       => $_->owed,
472                          charged    => $_->charged,
473                        };
474                      } $cust_main->open_cust_bill;
475       $return{open_invoices} = \@open;
476
477       my $sql = 'SELECT MAX(_date) FROM cust_bill WHERE custnum = ?';
478       my $sth = dbh->prepare($sql) or die  dbh->errstr;
479       $sth->execute($custnum)      or die $sth->errstr;
480       $return{'last_invoice_date'} = $sth->fetchrow_arrayref->[0];
481       $return{'last_invoice_date_pretty'} =
482         time2str('%m/%d/%Y', $return{'last_invoice_date'} );
483     }
484
485     #customer_info_short always has nobalance on..
486     $return{small_custview} =
487       small_custview( $cust_main,
488                       $return{countrydefault},
489                       ( $session->{'pkgnum'} ? 1 : 0 ), #nobalance
490                     );
491
492     $return{has_ship_address} = $cust_main->has_ship_address;
493     $return{status} = $cust_main->status;
494     $return{statuscolor} = $cust_main->statuscolor;
495
496     # compatibility: some places in selfservice use this to determine
497     # if there's a ship address
498     if ( $return{has_ship_address} ) {
499       $return{ship_last}  = $cust_main->last;
500       $return{ship_first} = $cust_main->first;
501     }
502
503     if (scalar($conf->config('support_packages'))) {
504       my @support_services = ();
505       foreach ($cust_main->support_services) {
506         my $seconds = $_->svc_x->seconds || 0;
507         my $time_remaining = (($seconds < 0) ? '-' : '' ).
508                              int(abs($seconds)/3600)."h".
509                              sprintf("%02d",(abs($seconds)%3600)/60)."m";
510         my $cust_pkg = $_->cust_pkg;
511         my $pkgnum = '';
512         my $pkg = '';
513         $pkgnum = $cust_pkg->pkgnum if $cust_pkg;
514         $pkg = $cust_pkg->part_pkg->pkg if $cust_pkg;
515         push @support_services, { svcnum => $_->svcnum,
516                                   time => $time_remaining,
517                                   pkgnum => $pkgnum,
518                                   pkg => $pkg,
519                                 };
520       }
521       $return{support_services} = \@support_services;
522     }
523
524     if ( $conf->config('prepayment_discounts-credit_type') ) {
525       #need to eval?
526       $return{discount_terms_hash} = { $cust_main->discount_terms_hash };
527     }
528
529   } elsif ( $session->{'svcnum'} ) { #no customer record
530
531     my $svc_acct = qsearchs('svc_acct', { 'svcnum' => $session->{'svcnum'} } )
532       or die "unknown svcnum";
533     $return{name} = $svc_acct->email;
534
535   } else {
536
537     return { 'error' => 'Expired session' }; #XXX redirect to login w/this err!
538
539   }
540
541   return { 'error'   => '',
542            'custnum' => $custnum,
543            %return,
544          };
545
546 }
547
548 sub customer_info_short {
549   my $p = shift;
550
551   my($context, $session, $custnum) = _custoragent_session_custnum($p);
552   return { 'error' => $session } if $context eq 'error';
553
554   my %return;
555
556   my $conf = new FS::Conf;
557
558   if ( $custnum ) { #customer record
559
560     my $search = { 'custnum' => $custnum };
561     $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
562     my $cust_main = qsearchs('cust_main', $search )
563       or return { 'error' => "unknown custnum $custnum" };
564
565     $return{display_custnum} = $cust_main->display_custnum;
566
567     if ( $session->{'pkgnum'} ) { 
568       $return{balance} = $cust_main->balance_pkgnum( $session->{'pkgnum'} );
569       #next_bill_date from cust_pkg?
570     } else {
571       $return{balance} = $cust_main->balance;
572       $return{next_bill_date} = $cust_main->next_bill_date;
573       $return{next_bill_date_pretty} =
574         $return{next_bill_date} ? time2str('%m/%d/%Y', $return{next_bill_date} )
575                                 : '(none)';
576     }
577     $return{balance_pretty} = money_pretty($return{balance});
578
579     $return{countrydefault} = scalar($conf->config('countrydefault'));
580
581     $return{small_custview} =
582       small_custview( $cust_main,
583                       $return{countrydefault},
584                       1, ##nobalance
585                     );
586
587     $return{name} = $cust_main->first. ' '. $cust_main->get('last');
588
589     $return{payby} = $cust_main->payby;
590
591     #none of these are terribly expensive if we want 'em...
592     for (@cust_main_editable_fields) {
593       $return{$_} = $cust_main->get($_);
594     }
595     #maybe a little more expensive, but it should be cached by now
596     for (@location_editable_fields) {
597       $return{$_} = $cust_main->bill_location->get($_);
598       $return{'ship_'.$_} = $cust_main->ship_location->get($_);
599     }
600  
601     if ( $cust_main->payby =~ /^(CARD|DCRD)$/ ) {
602       $return{payinfo} = $cust_main->paymask;
603       @return{'month', 'year'} = $cust_main->paydate_monthyear;
604     }
605     
606     my @invoicing_list = $cust_main->invoicing_list;
607     $return{'invoicing_list'} =
608       join(', ', grep { $_ !~ /^(POST|FAX)$/ } @invoicing_list );
609     $return{'postal_invoicing'} =
610       0 < ( grep { $_ eq 'POST' } @invoicing_list );
611
612     if ( $session->{'svcnum'} ) {
613       my $cust_svc = qsearchs('cust_svc', { 'svcnum' => $session->{'svcnum'} });
614       $return{'svc_label'} = ($cust_svc->label)[1] if $cust_svc;
615       $return{'svcnum'} = $session->{'svcnum'};
616     }
617
618   } elsif ( $session->{'svcnum'} ) { #no customer record
619
620     #uuh, not supproted yet... die?
621     return { 'error' => 'customer_info_short not yet supported as agent' };
622
623   } else {
624
625     return { 'error' => 'Expired session' }; #XXX redirect to login w/this err!
626
627   }
628
629   # this is here because this routine is called by both fs_ and ng_ main pages, where it appears
630   # it is not customer-specific, though it is only shown to authenticated customers
631   # it is not currently agent-specific, though at some point it might be
632   $return{'announcement'} = join(' ',$conf->config('selfservice-announcement')) || '';
633
634   return { 'error'          => '',
635            'custnum'        => $custnum,
636            %return,
637          };
638 }
639
640 sub customer_recurring {
641   my $p = shift;
642
643   my($context, $session, $custnum) = _custoragent_session_custnum($p);
644   return { 'error' => $session } if $context eq 'error';
645
646   my %return;
647
648   my $conf = new FS::Conf;
649
650   my $search = { 'custnum' => $custnum };
651   $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
652   my $cust_main = qsearchs('cust_main', $search )
653     or return { 'error' => "customer_info_short: unknown custnum $custnum" };
654
655   $return{'display_recurring'} = [ $cust_main->display_recurring ];
656
657   return { 'error'          => '',
658            'custnum'        => $custnum,
659            %return,
660          };
661 }
662
663 sub billing_history {
664   my $p = shift;
665
666   my($context, $session, $custnum) = _custoragent_session_custnum($p);
667   return { 'error' => $session } if $context eq 'error';
668
669   return { 'error' => 'No customer' } unless $custnum;
670
671   my $search = { 'custnum' => $custnum };
672   $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
673   my $cust_main = qsearchs('cust_main', $search )
674     or return { 'error' => "unknown custnum $custnum" };
675
676   my %return = ();
677
678   if ( $session->{'pkgnum'} ) { 
679     #$return{balance} = $cust_main->balance_pkgnum( $session->{'pkgnum'} );
680     #next_bill_date from cust_pkg?
681     return { 'error' => 'No history for package' };
682   }
683
684   $return{balance} = $cust_main->balance;
685   $return{balance_pretty} = money_pretty($return{balance});
686   $return{next_bill_date} = $cust_main->next_bill_date;
687   $return{next_bill_date_pretty} =
688     $return{next_bill_date} ? time2str('%m/%d/%Y', $return{next_bill_date} )
689                             : '(none)';
690
691   my $conf = new FS::Conf;
692
693   $return{'history'} = [
694     $cust_main->payment_history(
695       'line_items' => $conf->exists('selfservice-billing_history-line_items'),
696       'reverse_sort' => 1,
697     )
698   ];
699
700   $return{'money_char'} = $conf->config("money_char") || '$',
701
702   return \%return;
703
704 }
705
706 sub edit_info {
707   my $p = shift;
708   my $session = _cache->get($p->{'session_id'})
709     or return { 'error' => "Can't resume session" }; #better error message
710
711   my $custnum = $session->{'custnum'}
712     or return { 'error' => "no customer record" };
713
714   my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
715     or return { 'error' => "unknown custnum $custnum" };
716
717   my $new = new FS::cust_main { $cust_main->hash };
718
719   $new->set( $_ => $p->{$_} )
720     foreach grep { exists $p->{$_} } @cust_main_editable_fields;
721
722   if ( exists($p->{address1}) ) {
723     my $bill_location = FS::cust_location->new({
724         map { $_ => $p->{$_} } @location_editable_fields
725     });
726     # if this is unchanged from before, cust_main::replace will ignore it
727     $new->set('bill_location' => $bill_location);
728   }
729
730   if ( exists($p->{ship_address1}) ) {
731     my $ship_location = FS::cust_location->new({
732         map { $_ => $p->{"ship_$_"} } @location_editable_fields
733     });
734     if ( !grep { length($p->{"ship_$_"}) } @location_editable_fields ) {
735       # Selfservice unfortunately tries to indicate "same as billing 
736       # address" by sending all fields empty.  Did this ever work?
737       $ship_location = $cust_main->bill_location;
738     }
739     $new->set('ship_location' => $ship_location);
740   }
741   # but if it hasn't been passed in at all, leave ship_location alone--
742   # DON'T change it to match bill_location.
743
744   my $payby = '';
745   if (exists($p->{'payby'})) {
746     $p->{'payby'} =~ /^([A-Z]{4})$/
747       or return { 'error' => "illegal_payby " . $p->{'payby'} };
748     $payby = $1;
749   }
750
751   my $conf = new FS::Conf;
752
753   if ( $payby =~ /^(CARD|DCRD)$/ ) {
754
755     $new->paydate($p->{'year'}. '-'. $p->{'month'}. '-01');
756
757     if ( $new->payinfo eq $cust_main->paymask ) {
758       $new->payinfo($cust_main->payinfo);
759       $new->paycvv( $p->{'paycvv'} || $cust_main->paycvv );
760     } else {
761       $new->payinfo($p->{'payinfo'});
762       return { 'error' => 'CVV2 is required' }
763         if ! $p->{'paycvv'} && $conf->exists('selfservice-onfile_require_cvv');
764       $new->paycvv( $p->{'paycvv'} )
765     }
766
767     $new->set( 'payby' => $p->{'auto'} ? 'CARD' : 'DCRD' );
768
769   } elsif ( $payby =~ /^(CHEK|DCHK)$/ ) {
770
771     my $payinfo;
772     $p->{'payinfo1'} =~ /^([\dx]+)$/
773       or return { 'error' => "illegal account number ". $p->{'payinfo1'} };
774     my $payinfo1 = $1;
775      $p->{'payinfo2'} =~ /^([\dx\.]+)$/ # . turned on by echeck-country CA ?
776       or return { 'error' => "illegal ABA/routing number ". $p->{'payinfo2'} };
777     my $payinfo2 = $1;
778     $payinfo = $payinfo1. '@'. $payinfo2;
779
780     $new->payinfo( ($payinfo eq $cust_main->paymask)
781                      ? $cust_main->payinfo
782                      : $payinfo
783                  );
784
785     $new->set( 'payby' => $p->{'auto'} ? 'CHEK' : 'DCHK' );
786
787   } elsif ( $payby =~ /^(BILL)$/ ) {
788     #no-op
789   } elsif ( $payby ) {  #notyet ready
790     return { 'error' => "unknown payby $payby" };
791   }
792
793   my @invoicing_list;
794   if ( exists $p->{'invoicing_list'} || exists $p->{'postal_invoicing'} ) {
795     #false laziness with httemplate/edit/process/cust_main.cgi
796     @invoicing_list = split( /\s*\,\s*/, $p->{'invoicing_list'} );
797     push @invoicing_list, 'POST' if $p->{'postal_invoicing'};
798   } else {
799     @invoicing_list = $cust_main->invoicing_list;
800   }
801
802   my $error = $new->replace($cust_main, \@invoicing_list);
803   return { 'error' => $error } if $error;
804   #$cust_main = $new;
805   
806   return { 'error' => '' };
807 }
808
809 sub payment_info {
810   my $p = shift;
811   my $session = _cache->get($p->{'session_id'})
812     or return { 'error' => "Can't resume session" }; #better error message
813
814   ##
815   #generic
816   ##
817
818   my $conf = new FS::Conf;
819   use vars qw($payment_info); #cache for performance
820   unless ( $payment_info ) {
821
822     my %states = map { $_->state => 1 }
823                    qsearch('cust_main_county', {
824                      'country' => $conf->config('countrydefault') || 'US'
825                    } );
826
827     my %cust_paybys = map { $_ => 1 }
828                       map { FS::payby->payby2payment($_) }
829                           $conf->config('signup_server-payby');
830
831     my @cust_paybys = keys %cust_paybys;
832
833     $payment_info = {
834
835       #list all counties/states/countries
836       'cust_main_county' => 
837         [ map { $_->hashref } qsearch('cust_main_county', {}) ],
838
839       #shortcut for one-country folks
840       'states' =>
841         [ sort { $a cmp $b } keys %states ],
842
843       'card_types' => card_types(),
844
845       'withcvv'            => $conf->exists('selfservice-require_cvv'), #or enable optional cvv?
846       'require_cvv'        => $conf->exists('selfservice-require_cvv'),
847       'onfile_require_cvv' => $conf->exists('selfservice-onfile_require_cvv'),
848
849       'paytypes' => [ @FS::cust_main::paytypes ],
850
851       'paybys' => [ $conf->config('signup_server-payby') ],
852       'cust_paybys' => \@cust_paybys,
853
854       'stateid_label' => FS::Msgcat::_gettext('stateid'),
855       'stateid_state_label' => FS::Msgcat::_gettext('stateid_state'),
856
857       'show_ss'  => $conf->exists('show_ss'),
858       'show_stateid' => $conf->exists('show_stateid'),
859       'show_paystate' => $conf->exists('show_bankstate'),
860
861       'save_unchecked' => $conf->exists('selfservice-save_unchecked'),
862
863     };
864
865   }
866
867   ##
868   #customer-specific
869   ##
870
871   my %return = %$payment_info;
872
873   my $custnum = $session->{'custnum'};
874
875   my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
876     or return { 'error' => "unknown custnum $custnum" };
877
878   $return{'hide_payment_fields'} = [
879     map { 
880       my $pg = payment_gateway($cust_main, $_);
881       $pg && $pg->gateway_namespace eq 'Business::OnlineThirdPartyPayment';
882     } @{ $return{cust_paybys} }
883   ];
884
885   $return{balance} = $cust_main->balance; #XXX pkg-balances?
886
887   $return{payname} = $cust_main->payname
888                      || ( $cust_main->first. ' '. $cust_main->get('last') );
889
890   $return{$_} = $cust_main->bill_location->get($_) 
891     for qw(address1 address2 city state zip);
892
893   $return{payby} = $cust_main->payby;
894   $return{stateid_state} = $cust_main->stateid_state;
895
896   if ( $cust_main->payby =~ /^(CARD|DCRD)$/ ) {
897     $return{card_type} = cardtype($cust_main->payinfo);
898     $return{payinfo} = $cust_main->paymask;
899
900     @return{'month', 'year'} = $cust_main->paydate_monthyear;
901
902   }
903
904   if ( $cust_main->payby =~ /^(CHEK|DCHK)$/ ) {
905     my ($payinfo1, $payinfo2) = split '@', $cust_main->paymask;
906     $return{payinfo1} = $payinfo1;
907     $return{payinfo2} = $payinfo2;
908     $return{paytype}  = $cust_main->paytype;
909     $return{paystate} = $cust_main->paystate;
910     $return{payname}  = $cust_main->payname;    # override 'first/last name' default from above, if any.  Is instution-name here.  (#15819)
911   }
912
913   if ( $conf->config('prepayment_discounts-credit_type') ) {
914     #need to eval?
915     $return{discount_terms_hash} = { $cust_main->discount_terms_hash };
916   }
917
918   #doubleclick protection
919   my $_date = time;
920   $return{payunique} = "webui-MyAccount-$_date-$$-". rand() * 2**32; #new
921   $return{paybatch} = $return{payunique};  #back compat
922
923   $return{credit_card_surcharge_percentage} = $conf->config('credit-card-surcharge-percentage', $cust_main->agentnum);
924
925   return { 'error' => '',
926            %return,
927          };
928
929 }
930
931 #some false laziness with httemplate/process/payment.cgi - look there for
932 #ACH and CVV support stuff
933
934 sub validate_payment {
935   my $p = shift;
936
937   my $session = _cache->get($p->{'session_id'})
938     or return { 'error' => "Can't resume session" }; #better error message
939
940   my $custnum = $session->{'custnum'};
941
942   my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
943     or return { 'error' => "unknown custnum $custnum" };
944
945   $p->{'amount'} =~ /^\s*(\d+(\.\d{2})?)\s*$/
946     or return { 'error' => gettext('illegal_amount') };
947   my $amount = $1;
948   return { error => 'Amount must be greater than 0' } unless $amount > 0;
949
950   #false laziness w/tr-amount_fee.html, but we don't want selfservice users
951   #changing the hidden form values
952   my $conf = new FS::Conf;
953   my $fee_display = $conf->config('selfservice_process-display') || 'add';
954   my $fee_pkgpart = $conf->config('selfservice_process-pkgpart', $cust_main->agentnum);
955   my $fee_skip_first = $conf->exists('selfservice_process-skip_first');
956   if ( $fee_display eq 'add'
957          and $fee_pkgpart
958          and ! $fee_skip_first || scalar($cust_main->cust_pay)
959      )
960   {
961     my $fee_pkg = qsearchs('part_pkg', { pkgpart=>$fee_pkgpart } );
962     $amount = sprintf('%.2f', $amount + $fee_pkg->option('setup_fee') );
963   }
964
965   $p->{'discount_term'} =~ /^\s*(\d*)\s*$/
966     or return { 'error' => gettext('illegal_discount_term'). ': '. $p->{'discount_term'} };
967   my $discount_term = $1;
968
969   $p->{'payname'} =~ /^([\w \,\.\-\']+)$/
970     or return { 'error' => gettext('illegal_name'). " payname: ". $p->{'payname'} };
971   my $payname = $1;
972
973   $p->{'payunique'} =~ /^([\w \!\@\#\$\%\&\(\)\-\+\;\:\'\"\,\.\?\/\=]*)$/
974     or return { 'error' => gettext('illegal_text'). " payunique: ". $p->{'payunique'} };
975   my $payunique = $1;
976
977   $p->{'paybatch'} =~ /^([\w \!\@\#\$\%\&\(\)\-\+\;\:\'\"\,\.\?\/\=]*)$/
978     or return { 'error' => gettext('illegal_text'). " paybatch: ". $p->{'paybatch'} };
979   my $paybatch = $1;
980
981   $payunique = $paybatch if ! length($payunique) && length($paybatch);
982
983   $p->{'payby'} ||= 'CARD';
984   $p->{'payby'} =~ /^([A-Z]{4})$/
985     or return { 'error' => "illegal_payby " . $p->{'payby'} };
986   my $payby = $1;
987
988   #false laziness w/process/payment.cgi
989   my $payinfo;
990   my $paycvv = '';
991   if ( $payby eq 'CHEK' || $payby eq 'DCHK' ) {
992   
993     $p->{'payinfo1'} =~ /^([\dx]+)$/
994       or return { 'error' => "illegal account number ". $p->{'payinfo1'} };
995     my $payinfo1 = $1;
996      $p->{'payinfo2'} =~ /^([\dx]+)$/
997       or return { 'error' => "illegal ABA/routing number ". $p->{'payinfo2'} };
998     my $payinfo2 = $1;
999     $payinfo = $payinfo1. '@'. $payinfo2;
1000
1001     $payinfo = $cust_main->payinfo
1002       if $cust_main->paymask eq $payinfo;
1003    
1004   } elsif ( $payby eq 'CARD' || $payby eq 'DCRD' ) {
1005    
1006     $payinfo = $p->{'payinfo'};
1007
1008     my $onfile = 0;
1009
1010     #more intelligent matching will be needed here if you change
1011     #card_masking_method and don't remove existing paymasks
1012     if ( $cust_main->paymask eq $payinfo ) {
1013       $payinfo = $cust_main->payinfo;
1014       $onfile = 1;
1015     }
1016
1017     $payinfo =~ s/\D//g;
1018     $payinfo =~ /^(\d{13,16}|\d{8,9})$/
1019       or return { 'error' => gettext('invalid_card') }; # . ": ". $self->payinfo
1020     $payinfo = $1;
1021
1022     validate($payinfo)
1023       or return { 'error' => gettext('invalid_card') }; # . ": ". $self->payinfo
1024     return { 'error' => gettext('unknown_card_type') }
1025       if !$cust_main->tokenized($payinfo) && cardtype($payinfo) eq "Unknown";
1026
1027     if ( length($p->{'paycvv'}) && $p->{'paycvv'} !~ /^\s*$/ ) {
1028       if ( cardtype($payinfo) eq 'American Express card' ) {
1029         $p->{'paycvv'} =~ /^\s*(\d{4})\s*$/
1030           or return { 'error' => "CVV2 (CID) for American Express cards is four digits." };
1031         $paycvv = $1;
1032       } else {
1033         $p->{'paycvv'} =~ /^\s*(\d{3})\s*$/
1034           or return { 'error' => "CVV2 (CVC2/CID) is three digits." };
1035         $paycvv = $1;
1036       }
1037     } elsif ( $conf->exists('selfservice-onfile_require_cvv') ) {
1038       return { 'error' => 'CVV2 is required' };
1039     } elsif ( !$onfile && $conf->exists('selfservice-require_cvv') ) {
1040       return { 'error' => 'CVV2 is required' };
1041     }
1042   
1043   } else {
1044     die "unknown payby $payby";
1045   }
1046
1047   my %payby2fields = (
1048     'CARD' => [ qw( paystart_month paystart_year payissue payip
1049                     address1 address2 city state zip country    ) ],
1050     'CHEK' => [ qw( ss paytype paystate stateid stateid_state payip ) ],
1051   );
1052
1053   my $card_type = '';
1054   $card_type = cardtype($payinfo) if $payby eq 'CARD';
1055
1056   { 
1057     'cust_main'      => $cust_main, #XXX or just custnum??
1058     'amount'         => sprintf('%.2f', $amount),
1059     'payby'          => $payby,
1060     'payinfo'        => $payinfo,
1061     'paymask'        => $cust_main->mask_payinfo( $payby, $payinfo ),
1062     'card_type'      => $card_type,
1063     'paydate'        => $p->{'year'}. '-'. $p->{'month'}. '-01',
1064     'paydate_pretty' => $p->{'month'}. ' / '. $p->{'year'},
1065     'month'          => $p->{'month'},
1066     'year'           => $p->{'year'},
1067     'payname'        => $payname,
1068     'payunique'      => $payunique,
1069     'paybatch'       => $paybatch,
1070     'paycvv'         => $paycvv,
1071     'payname'        => $payname,
1072     'discount_term'  => $discount_term,
1073     'pkgnum'         => $session->{'pkgnum'},
1074     map { $_ => $p->{$_} } ( @{ $payby2fields{$payby} },
1075                              qw( save auto ),
1076                            )
1077   };
1078
1079 }
1080
1081 sub store_payment {
1082   my $p = shift;
1083
1084   my $validate = validate_payment($p);
1085   return $validate if $validate->{'error'};
1086
1087   my $conf = new FS::Conf;
1088   my $timeout = $conf->config('selfservice-session_timeout') || '1 hour'; #?
1089   _cache->set( 'payment_'.$p->{'session_id'}, $validate, $timeout );
1090
1091   +{ map { $_=>$validate->{$_} }
1092       qw( card_type paymask payname paydate_pretty month year amount
1093           address1 address2 city state zip country
1094         )
1095   };
1096
1097 }
1098
1099 sub process_stored_payment {
1100   my $p = shift;
1101
1102   my $session_id = $p->{'session_id'};
1103
1104   my $payment_info = _cache->get( "payment_$session_id" )
1105     or return { 'error' => "Can't resume session" }; #better error message
1106
1107   do_process_payment($payment_info);
1108
1109 }
1110
1111 sub process_payment {
1112   my $p = shift;
1113
1114   my $payment_info = validate_payment($p);
1115   return $payment_info if $payment_info->{'error'};
1116
1117   do_process_payment($payment_info);
1118
1119 }
1120
1121 sub do_process_payment {
1122   my $validate = shift;
1123
1124   my $cust_main = $validate->{'cust_main'};
1125
1126   my $amount = delete $validate->{'amount'};
1127   my $paynum = '';
1128
1129   my $payby = delete $validate->{'payby'};
1130
1131   if ( $validate->{'save'} ) {
1132     my $new = new FS::cust_main { $cust_main->hash };
1133     if ($payby eq 'CARD' || $payby eq 'DCRD') {
1134       $new->set( $_ => $validate->{$_} )
1135         foreach qw( payname paystart_month paystart_year payissue payip );
1136       $new->set( 'payby' => $validate->{'auto'} ? 'CARD' : 'DCRD' );
1137
1138       my $bill_location = FS::cust_location->new({
1139           map { $_ => $validate->{$_} } 
1140           qw(address1 address2 city state country zip)
1141       }); # county?
1142       $new->set('bill_location' => $bill_location);
1143       # but don't allow the service address to change this way.
1144
1145     } elsif ($payby eq 'CHEK' || $payby eq 'DCHK') {
1146       $new->set( $_ => $validate->{$_} )
1147         foreach qw( payname payip paytype paystate
1148                     stateid stateid_state );
1149       $new->set( 'payby' => $validate->{'auto'} ? 'CHEK' : 'DCHK' );
1150     }
1151     $new->payinfo( $validate->{'payinfo'} ); #to properly set paymask
1152     $new->set( 'paydate' => $validate->{'paydate'} );
1153     my $error = $new->replace($cust_main);
1154     if ( $error ) {
1155       #no, this causes customers to process their payments again
1156       #return { 'error' => $error };
1157       #XXX just warn verosely for now so i can figure out how these happen in
1158       # the first place, eventually should redirect them to the "change
1159       #address" page but indicate if the payment processed?
1160       delete($validate->{'payinfo'}); #don't want to log this!
1161       warn "WARNING: error changing customer info when processing payment (not returning to customer as a processing error): $error\n".
1162            "NEW: ". Dumper($new)."\n".
1163            "OLD: ". Dumper($cust_main)."\n".
1164            "PACKET: ". Dumper($validate)."\n";
1165     } else {
1166       $cust_main = $new;
1167     }
1168   }
1169
1170   my $error = $cust_main->realtime_bop( $FS::payby::payby2bop{$payby}, $amount,
1171     'quiet'       => 1,
1172     'manual'      => 1,
1173     'selfservice' => 1,
1174     'paynum_ref'  => \$paynum,
1175     %$validate,
1176   );
1177   return { 'error' => $error } if $error;
1178
1179   #no error, so order the fee package if applicable...
1180   my $conf = new FS::Conf;
1181   my $fee_pkgpart = $conf->config('selfservice_process-pkgpart', $cust_main->agentnum);
1182   my $fee_skip_first = $conf->exists('selfservice_process-skip_first');
1183   
1184   if ( $fee_pkgpart and ! $fee_skip_first || scalar($cust_main->cust_pay) ) {
1185
1186     my $cust_pkg = new FS::cust_pkg { 'pkgpart' => $fee_pkgpart };
1187
1188     $error = $cust_main->order_pkg( 'cust_pkg' => $cust_pkg );
1189     return { 'error' => "payment processed successfully, but error ordering fee: $error" }
1190       if $error;
1191
1192     #and generate an invoice for it now too
1193     $error = $cust_main->bill( 'pkg_list' => [ $cust_pkg ] );
1194     return { 'error' => "payment processed and fee ordered sucessfully, but error billing fee: $error" }
1195       if $error;
1196
1197   }
1198
1199   $cust_main->apply_payments;
1200
1201   my $cust_pay = '';
1202   my $receipt_html = '';
1203   if ($paynum) {
1204       # currently supported for realtime CC only; send receipt data to SS
1205       $cust_pay = qsearchs('cust_pay', { 'paynum' => $paynum } );
1206       if($cust_pay) {
1207         $receipt_html = qq!
1208 <TABLE BGCOLOR="#cccccc" BORDER=0 CELLSPACING=2>
1209
1210 <TR>
1211   <TD ALIGN="right">Payment#</TD>
1212   <TD BGCOLOR="#FFFFFF"><B>! . $cust_pay->paynum . qq!</B></TD>
1213 </TR>
1214
1215 <TR>
1216   <TD ALIGN="right">Date</TD>
1217
1218   <TD BGCOLOR="#FFFFFF"><B>! . 
1219         time2str("%a&nbsp;%b&nbsp;%o,&nbsp;%Y&nbsp;%r", $cust_pay->_date)
1220                                                             . qq!</B></TD>
1221 </TR>
1222
1223
1224 <TR>
1225   <TD ALIGN="right">Amount</TD>
1226   <TD BGCOLOR="#FFFFFF"><B>! . sprintf('%.2f', $cust_pay->paid) . qq!</B></TD>
1227
1228 </TR>
1229
1230 <TR>
1231   <TD ALIGN="right">Payment method</TD>
1232   <TD BGCOLOR="#FFFFFF"><B>! . $cust_pay->payby_name .' #'. $cust_pay->paymask
1233                                                                 . qq!</B></TD>
1234 </TR>
1235
1236 </TABLE>
1237 !;
1238       }
1239   }
1240
1241   if ( $cust_pay ) {
1242
1243     return {
1244       'error'        => '',
1245       'amount'       => sprintf('%.2f', $cust_pay->paid),
1246       'date'         => $cust_pay->_date,
1247       'date_pretty'  => time2str('%Y-%m-%d', $cust_pay->_date),
1248       'time_pretty'  => time2str('%T', $cust_pay->_date),
1249       'auth_num'     => $cust_pay->auth,
1250       'order_num'    => $cust_pay->order_number,
1251       'receipt_html' => $receipt_html,
1252     };
1253
1254   } else {
1255
1256     return {
1257       'error'        => '',
1258       'receipt_html' => '',
1259     };
1260
1261   }
1262
1263 }
1264
1265 sub realtime_collect {
1266   my $p = shift;
1267
1268   my $session = _cache->get($p->{'session_id'})
1269     or return { 'error' => "Can't resume session" }; #better error message
1270
1271   my $custnum = $session->{'custnum'};
1272
1273   my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1274     or return { 'error' => "unknown custnum $custnum" };
1275
1276   my $amount;
1277   if ( $p->{'amount'} ) {
1278     $amount = $p->{'amount'};
1279   }
1280   elsif ( $session->{'pkgnum'} ) {
1281     $amount = $cust_main->balance_pkgnum( $session->{'pkgnum'} );
1282   }
1283   else {
1284     $amount = $cust_main->balance;
1285   }
1286
1287   my $error = $cust_main->realtime_collect(
1288     'method'     => $p->{'method'},
1289     'amount'     => $amount,
1290     'pkgnum'     => $session->{'pkgnum'},
1291     'session_id' => $p->{'session_id'},
1292     'apply'      => 1,
1293     'selfservice'=> 1,
1294   );
1295   return { 'error' => $error } unless ref( $error );
1296
1297   return { 'error' => '', amount => $amount, %$error };
1298 }
1299
1300 sub start_thirdparty {
1301   my $p = shift;
1302   my $session = _cache->get($p->{'session_id'})
1303     or return { 'error' => "Can't resume session" }; #better error message
1304   my $custnum = $session->{'custnum'};
1305   my $cust_main = FS::cust_main->by_key($custnum);
1306   
1307   my $amount = $p->{'amount'}
1308     or return { error => 'no amount' };
1309
1310   my $result = $cust_main->create_payment(
1311     'method'      => $p->{'method'},
1312     'amount'      => $p->{'amount'},
1313     'pkgnum'      => $session->{'pkgnum'},
1314     'session_id'  => $p->{'session_id'},
1315   );
1316   
1317   if ( ref($result) ) { # hashref or error
1318     return $result;
1319   } else {
1320     return { error => $result };
1321   }
1322 }
1323
1324 sub finish_thirdparty {
1325   my $p = shift;
1326   my $session_id = delete $p->{'session_id'};
1327   my $session = _cache->get($session_id)
1328     or return { 'error' => "Can't resume session" };
1329   my $custnum = $session->{'custnum'};
1330   my $cust_main = FS::cust_main->by_key($custnum);
1331
1332   if ( $p->{_cancel} ) {
1333     # customer backed out of making a payment
1334     return $cust_main->cancel_payment( $session_id );
1335   }
1336   my $result = $cust_main->execute_payment( $session_id, %$p );
1337   if ( ref($result) ) {
1338     return $result;
1339   } else {
1340     return { error => $result };
1341   }
1342 }
1343
1344 sub process_payment_order_pkg {
1345   my $p = shift;
1346
1347   my $hr = process_payment($p);
1348   return $hr if $hr->{'error'};
1349
1350   order_pkg($p);
1351 }
1352
1353 sub process_payment_order_renew {
1354   my $p = shift;
1355
1356   my $hr = process_payment($p);
1357   return $hr if $hr->{'error'};
1358
1359   order_renew($p);
1360 }
1361
1362 sub process_prepay {
1363
1364   my $p = shift;
1365
1366   my $session = _cache->get($p->{'session_id'})
1367     or return { 'error' => "Can't resume session" }; #better error message
1368
1369   my %return;
1370
1371   my $custnum = $session->{'custnum'};
1372
1373   my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1374     or return { 'error' => "unknown custnum $custnum" };
1375
1376   my( $amount, $seconds, $upbytes, $downbytes, $totalbytes ) = ( 0, 0, 0, 0, 0 );
1377   my $error = $cust_main->recharge_prepay( $p->{'prepaid_cardnum'},
1378                                            \$amount,
1379                                            \$seconds,
1380                                            \$upbytes,
1381                                            \$downbytes,
1382                                            \$totalbytes,
1383                                          );
1384
1385   return { 'error' => $error } if $error;
1386
1387   return { 'error'     => '',
1388            'amount'    => $amount,
1389            'seconds'   => $seconds,
1390            'duration'  => duration_exact($seconds),
1391            'upbytes'   => $upbytes,
1392            'upload'    => FS::UI::bytecount::bytecount_unexact($upbytes),
1393            'downbytes' => $downbytes,
1394            'download'  => FS::UI::bytecount::bytecount_unexact($downbytes),
1395            'totalbytes'=> $totalbytes,
1396            'totalload' => FS::UI::bytecount::bytecount_unexact($totalbytes),
1397          };
1398
1399 }
1400
1401 sub invoice {
1402   my $p = shift;
1403   my $session = _cache->get($p->{'session_id'})
1404     or return { 'error' => "Can't resume session" }; #better error message
1405
1406   my $custnum = $session->{'custnum'};
1407
1408   my $invnum = $p->{'invnum'};
1409
1410   my $cust_bill = qsearchs('cust_bill', { 'invnum'  => $invnum,
1411                                           'custnum' => $custnum } )
1412     or return { 'error' => "Can't find invnum" };
1413
1414   #my %return;
1415
1416   return { 'error'        => '',
1417            'invnum'       => $invnum,
1418            'invoice_text' => join('', $cust_bill->print_text ),
1419            'invoice_html' => $cust_bill->print_html( { unsquelch_cdr => 1 } ),
1420          };
1421
1422 }
1423
1424 sub invoice_pdf {
1425   my $p = shift;
1426   my $session = _cache->get($p->{'session_id'})
1427     or return { 'error' => "Can't resume session" }; #better error message
1428
1429   my $custnum = $session->{'custnum'};
1430
1431   my $invnum = $p->{'invnum'};
1432
1433   my $cust_bill = qsearchs('cust_bill', { 'invnum'  => $invnum,
1434                                           'custnum' => $custnum } )
1435     or return { 'error' => "Can't find invnum" };
1436
1437   #my %return;
1438
1439   return { 'error'       => '',
1440            'invnum'      => $invnum,
1441            'invoice_pdf' => $cust_bill->print_pdf({
1442                               'unsquelch_cdr' => 1,
1443                               'locale'        => $p->{'locale'},
1444                             }),
1445          };
1446
1447 }
1448
1449 sub legacy_invoice {
1450   my $p = shift;
1451   my $session = _cache->get($p->{'session_id'})
1452     or return { 'error' => "Can't resume session" }; #better error message
1453
1454   my $custnum = $session->{'custnum'};
1455
1456   my $legacyinvnum = $p->{'legacyinvnum'};
1457
1458   my %hash = (
1459     'legacyinvnum' => $legacyinvnum,
1460     'custnum'      => $custnum,
1461   );
1462
1463   my $legacy_cust_bill =
1464          qsearchs('legacy_cust_bill', { %hash, 'locale' => $p->{'locale'} } )
1465       || qsearchs('legacy_cust_bill', \%hash )
1466     or return { 'error' => "Can't find legacyinvnum" };
1467
1468   #my %return;
1469
1470   return { 'error'        => '',
1471            'legacyinvnum' => $legacyinvnum,
1472            'legacyid'     => $legacy_cust_bill->legacyid,
1473            'invoice_html' => $legacy_cust_bill->content_html,
1474          };
1475
1476 }
1477
1478 sub legacy_invoice_pdf {
1479   my $p = shift;
1480   my $session = _cache->get($p->{'session_id'})
1481     or return { 'error' => "Can't resume session" }; #better error message
1482
1483   my $custnum = $session->{'custnum'};
1484
1485   my $legacyinvnum = $p->{'legacyinvnum'};
1486
1487   my $legacy_cust_bill = qsearchs('legacy_cust_bill', {
1488     'legacyinvnum' => $legacyinvnum,
1489     'custnum'      => $custnum,
1490   }) or return { 'error' => "Can't find legacyinvnum" };
1491
1492   #my %return;
1493
1494   return { 'error'        => '',
1495            'legacyinvnum' => $legacyinvnum,
1496            'legacyid'     => $legacy_cust_bill->legacyid,
1497            'invoice_pdf'  => $legacy_cust_bill->content_pdf,
1498          };
1499
1500 }
1501
1502 sub invoice_logo {
1503   my $p = shift;
1504
1505   #sessioning for this?  how do we get the session id to the backend invoice
1506   # template so it can add it to the link, blah
1507
1508   my $agentnum = '';
1509   if ( $p->{'invnum'} ) {
1510     my $cust_bill = qsearchs('cust_bill', { 'invnum' => $p->{'invnum'} } )
1511       or return { 'error' => 'unknown invnum' };
1512     $agentnum = $cust_bill->cust_main->agentnum;
1513   }
1514
1515   my $templatename = $p->{'template'} || $p->{'templatename'};
1516
1517   #false laziness-ish w/view/cust_bill-logo.cgi
1518
1519   my $conf = new FS::Conf;
1520   if ( $templatename =~ /^([^\.\/]*)$/ && $conf->exists("logo_$1.png") ) {
1521     $templatename = "_$1";
1522   } else {
1523     $templatename = '';
1524   }
1525
1526   my $filename = "logo$templatename.png";
1527
1528   return { 'error'        => '',
1529            'logo'         => $conf->config_binary($filename, $agentnum),
1530            'content_type' => 'image/png', #should allow gif, jpg too
1531          };
1532 }
1533
1534
1535 sub list_invoices {
1536   my $p = shift;
1537   my $session = _cache->get($p->{'session_id'})
1538     or return { 'error' => "Can't resume session" }; #better error message
1539
1540   my $custnum = $session->{'custnum'};
1541
1542   my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1543     or return { 'error' => "unknown custnum $custnum" };
1544
1545   my $conf = new FS::Conf;
1546
1547   my @legacy_cust_bill = $cust_main->legacy_cust_bill;
1548
1549   my @cust_bill = grep ! $_->hide, $cust_main->cust_bill;
1550
1551   my $balance = 0;
1552   my $invoices = [
1553     map {
1554       #not super efficient, we also run cust_bill_pay/cust_credited inside owed
1555       my @payments_and_credits = sort {$b->_date <=> $a->_date} ($_->cust_bill_pay,$_->cust_credited);
1556       my $owed = $_->owed;
1557       $balance += $owed;
1558       +{ 'invnum'       => $_->invnum,
1559          '_date'        => $_->_date,
1560          'date'         => time2str("%b %o, %Y", $_->_date),
1561          'date_short'   => time2str("%m-%d-%Y",  $_->_date),
1562          'previous'     => sprintf('%.2f', ($_->previous)[0]),
1563          'charged'      => sprintf('%.2f', $_->charged),
1564          'owed'         => sprintf('%.2f', $owed),
1565          'balance'      => sprintf('%.2f', $balance),
1566          'lastpay'      => @payments_and_credits 
1567                            ? time2str("%b %o, %Y", $payments_and_credits[0]->_date)
1568                            : '',
1569       }
1570     } @cust_bill
1571   ];
1572
1573   return  { 'error'       => '',
1574             'balance'     => $cust_main->balance,
1575             'money_char'  => $conf->config("money_char") || '$',
1576             'invoices'    => $invoices,
1577             'legacy_invoices' => [
1578               map {
1579                     +{ 'legacyinvnum' => $_->legacyinvnum,
1580                        'legacyid'     => $_->legacyid,
1581                        '_date'        => $_->_date,
1582                        'date'         => time2str("%b %o, %Y", $_->_date),
1583                        'date_short'   => time2str("%m-%d-%Y",  $_->_date),
1584                        'charged'      => sprintf('%.2f', $_->charged),
1585                        'has_content'  => (    length($_->content_pdf)
1586                                            || length($_->content_html) ),
1587                      }
1588                   }
1589                   @legacy_cust_bill
1590             ],
1591           };
1592 }
1593
1594 sub cancel {
1595   my $p = shift;
1596   my $session = _cache->get($p->{'session_id'})
1597     or return { 'error' => "Can't resume session" }; #better error message
1598
1599   my $custnum = $session->{'custnum'};
1600
1601   my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1602     or return { 'error' => "unknown custnum $custnum" };
1603
1604   my @errors = $cust_main->cancel( 'quiet'=>1 );
1605
1606   my $error = scalar(@errors) ? join(' / ', @errors) : '';
1607
1608   return { 'error' => $error };
1609
1610 }
1611
1612 sub list_pkgs {
1613   my $p = shift;
1614
1615   my($context, $session, $custnum) = _custoragent_session_custnum($p);
1616   return { 'error' => $session } if $context eq 'error';
1617
1618   my $search = { 'custnum' => $custnum };
1619   $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
1620   my $cust_main = qsearchs('cust_main', $search )
1621     or return { 'error' => "unknown custnum $custnum" };
1622
1623   my $conf = new FS::Conf;
1624   my $immutable = $conf->exists('selfservice_immutable-package');
1625   
1626 # the duplication below is necessary:
1627 # 1. to maintain the current buggy behaviour wrt the cust_pkg and part_pkg
1628 # hashes overwriting each other (setup and no_auto fields). Fixing that is a
1629 # non-backwards-compatible change breaking the software of anyone using the API
1630 # instead of the stock selfservice
1631 # 2. to return cancelled packages as well - for wholesale and non-wholesale
1632   if( $conf->exists('selfservice_server-view-wholesale') ) {
1633     return { 'svcnum'   => $session->{'svcnum'},
1634             'custnum'  => $custnum,
1635             'cust_pkg' => [ map {
1636                           { $_->hash,
1637                             immutable => $immutable,
1638                             part_pkg => [ map $_->hashref, $_->part_pkg ],
1639                             part_svc =>
1640                               [ map $_->hashref, $_->available_part_svc ],
1641                             cust_svc => 
1642                               [ map { my $ref = { $_->hash,
1643                                                   label => [ $_->label ],
1644                                                 };
1645                                       $ref->{_password} = $_->svc_x->_password
1646                                         if $context eq 'agent'
1647                                         && $conf->exists('agent-showpasswords')
1648                                         && $_->part_svc->svcdb eq 'svc_acct';
1649                                       $ref;
1650                                     } $_->cust_svc
1651                               ],
1652                           };
1653                         } $cust_main->cust_pkg
1654                   ],
1655     'small_custview' =>
1656       small_custview( $cust_main, $conf->config('countrydefault') ),
1657     'wholesale_view' => 1,
1658     'login_svcpart' => [ $conf->config('selfservice_server-login_svcpart') ],
1659     'date_format' => $conf->config('date_format') || '%m/%d/%Y',
1660     'lnp' => $conf->exists('svc_phone-lnp'),
1661       };
1662   }
1663
1664   { 'svcnum'   => $session->{'svcnum'},
1665     'custnum'  => $custnum,
1666     'cust_pkg' => [ map {
1667                           my $primary_cust_svc = $_->primary_cust_svc;
1668                           +{ $_->hash,
1669                             $_->part_pkg->hash,
1670                             immutable   => $immutable,
1671                             pkg_label   => $_->pkg_locale,
1672                             status      => $_->status,
1673                             statuscolor => $_->statuscolor,
1674                             part_svc =>
1675                               [ map { $_->hashref }
1676                                   grep { $_->selfservice_access ne 'hidden' }
1677                                     $_->available_part_svc
1678                               ],
1679                             cust_svc => 
1680                               [ map { my $ref = { $_->hash,
1681                                                   label => [ $_->label ],
1682                                                 };
1683                                       $ref->{_password} = $_->svc_x->_password
1684                                         if $context eq 'agent'
1685                                         && $conf->exists('agent-showpasswords')
1686                                         && $_->part_svc->svcdb eq 'svc_acct';
1687                                       $ref->{svchash} = { $_->svc_x->hash } if 
1688                                         $_->part_svc->svcdb eq 'svc_phone';
1689                                       $ref->{svchash}->{svcpart} =  $_->part_svc->svcpart
1690                                         if $_->part_svc->svcdb eq 'svc_phone'; # hack
1691                                       $ref;
1692                                     }
1693                                   grep { $_->part_svc->selfservice_access ne 'hidden' }
1694                                     $_->cust_svc
1695                               ],
1696                             primary_cust_svc =>
1697                               $primary_cust_svc
1698                                 ? { $primary_cust_svc->hash,
1699                                     label => [ $primary_cust_svc->label ],
1700                                     finger => $primary_cust_svc->svc_x->finger, #uuh
1701                                     $primary_cust_svc->part_svc->hash,
1702                                   }
1703                                 : {}, #'' ?
1704                           };
1705                         } $cust_main->ncancelled_pkgs
1706                   ],
1707     'small_custview' =>
1708       small_custview( $cust_main, $conf->config('countrydefault') ),
1709     'date_format' => $conf->config('date_format') || '%m/%d/%Y',
1710   };
1711
1712 }
1713
1714 sub list_svcs {
1715   my $p = shift;
1716
1717   my($context, $session, $custnum) = _custoragent_session_custnum($p);
1718   return { 'error' => $session } if $context eq 'error';
1719
1720   my $conf = new FS::Conf;
1721
1722   my $hide_usage = $conf->exists('selfservice_hide-usage') ? 1 : 0;
1723   my $search = { 'custnum' => $custnum };
1724   $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
1725   my $cust_main = qsearchs('cust_main', $search )
1726     or return { 'error' => "unknown custnum $custnum" };
1727
1728   my $pkgnum = $session->{'pkgnum'} || $p->{'pkgnum'} || '';
1729   if ( ! $pkgnum && $p->{'svcnum'} ) {
1730     my $cust_svc = qsearchs('cust_svc', { 'svcnum' => $p->{'svcnum'} } );
1731     $pkgnum = $cust_svc->pkgnum if $cust_svc;
1732   }
1733
1734   my @cust_svc = ();
1735   my @cust_pkg_usage = ();
1736   foreach my $cust_pkg ( $p->{'ncancelled'} 
1737                          ? $cust_main->ncancelled_pkgs
1738                          : $cust_main->unsuspended_pkgs ) {
1739     next if $pkgnum && $cust_pkg->pkgnum != $pkgnum;
1740     push @cust_svc, @{[ $cust_pkg->cust_svc ]}; #@{[ ]} to force array context
1741     push @cust_pkg_usage, $cust_pkg->cust_pkg_usage;
1742   }
1743
1744   @cust_svc = grep { $_->part_svc->selfservice_access ne 'hidden' } @cust_svc;
1745   my %usage_pools;
1746   if (!$hide_usage) {
1747     foreach (@cust_pkg_usage) {
1748       my $part = $_->part_pkg_usage;
1749       my $tag = $part->description . ($part->shared ? 1 : 0);
1750       my $row = $usage_pools{$tag} 
1751             ||= [ $part->description, 0, 0, $part->shared ? 1 : 0 ];
1752       $row->[1] += sprintf('%.1f', $_->minutes); # minutes remaining
1753       $row->[2] += $part->minutes; # minutes total
1754     }
1755   } # otherwise just leave them empty
1756
1757   if ( $p->{'svcdb'} ) {
1758     my $svcdb = ref($p->{'svcdb'}) eq 'HASH'
1759                   ? $p->{'svcdb'}
1760                   : ref($p->{'svcdb'}) eq 'ARRAY'
1761                     ? { map { $_=>1 } @{ $p->{'svcdb'} } }
1762                     : { $p->{'svcdb'} => 1 };
1763     @cust_svc = grep $svcdb->{ $_->part_svc->svcdb }, @cust_svc
1764   }
1765
1766   #@svc_x = sort { $a->domain cmp $b->domain || $a->username cmp $b->username }
1767   #              @svc_x;
1768
1769   my @svcs; # stuff to return to the client
1770   my %bytes_used_total; # for _used columns only
1771   foreach my $cust_svc (@cust_svc) {
1772     my $svc_x = $cust_svc->svc_x;
1773     my($label, $value) = $cust_svc->label;
1774     my $part_svc = $cust_svc->part_svc;
1775     my $svcdb = $part_svc->svcdb;
1776     my $cust_pkg = $cust_svc->cust_pkg;
1777     my $part_pkg = $cust_pkg->part_pkg;
1778
1779     my %hash = (
1780       'svcnum'         => $cust_svc->svcnum,
1781       'display_svcnum' => $cust_svc->display_svcnum,
1782       'svcdb'          => $svcdb,
1783       'label'          => $label,
1784       'value'          => $value,
1785       'pkg_label'      => $cust_pkg->pkg_locale,
1786       'pkg_status'     => $cust_pkg->status,
1787       'readonly'       => ($part_svc->selfservice_access eq 'readonly'),
1788     );
1789
1790     # would it make sense to put this in a svc_* method?
1791
1792     if (!$hide_usage and grep(/^$svcdb$/, qw(svc_acct svc_broadband)) and $part_svc->part_export_usage) {
1793       my $last_bill = $cust_pkg->last_bill || 0;
1794       my $now = time;
1795       my $up_used = $cust_svc->attribute_since_sqlradacct($last_bill,$now,'AcctInputOctets');
1796       my $down_used = $cust_svc->attribute_since_sqlradacct($last_bill,$now,'AcctOutputOctets');
1797       %hash = (
1798         %hash,
1799         'seconds_used'    => $cust_svc->seconds_since_sqlradacct($last_bill,$now),
1800         'upbytes_used'    => display_bytecount($up_used),
1801         'downbytes_used'  => display_bytecount($down_used),
1802         'totalbytes_used' => display_bytecount($up_used + $down_used)
1803       );
1804       $bytes_used_total{'seconds_used'} += $hash{'seconds_used'};
1805       $bytes_used_total{'upbytes_used'} += $up_used;
1806       $bytes_used_total{'downbytes_used'} += $down_used;
1807       $bytes_used_total{'totalbytes_used'} += $up_used + $down_used;
1808     }
1809
1810     if ( $svcdb eq 'svc_acct' ) {
1811       foreach (qw(username email finger seconds)) {
1812         $hash{$_} = $svc_x->$_;
1813       }
1814
1815       if (!$hide_usage) {
1816         %hash = (
1817           %hash,
1818           'upbytes'    => display_bytecount($svc_x->upbytes),
1819           'downbytes'  => display_bytecount($svc_x->downbytes),
1820           'totalbytes' => display_bytecount($svc_x->totalbytes),
1821
1822           'recharge_amount'  => $part_pkg->option('recharge_amount',1),
1823           'recharge_seconds' => $part_pkg->option('recharge_seconds',1),
1824           'recharge_upbytes'    =>
1825             display_bytecount($part_pkg->option('recharge_upbytes',1)),
1826           'recharge_downbytes'  =>
1827             display_bytecount($part_pkg->option('recharge_downbytes',1)),
1828           'recharge_totalbytes' =>
1829             display_bytecount($part_pkg->option('recharge_totalbytes',1)),
1830           # more...
1831         );
1832       }
1833
1834     } elsif ( $svcdb eq 'svc_dsl' ) {
1835
1836       $hash{'phonenum'} = $svc_x->phonenum;
1837       if ( $svc_x->first || $svc_x->get('last') || $svc_x->company ) {
1838         $hash{'name'} = $svc_x->first. ' '. $svc_x->get('last');
1839         $hash{'name'} = $svc_x->company. ' ('. $hash{'name'}. ')'
1840           if $svc_x->company;
1841       } else {
1842         $hash{'name'} = $cust_main->name;
1843       }
1844       # no usage to hide here
1845
1846     } elsif ( $svcdb eq 'svc_phone' or $svcdb eq 'svc_pbx' ) {
1847       if (!$hide_usage) {
1848         # could potentially show lots of things...
1849         $hash{'outbound'} = 1;
1850         $hash{'inbound'}  = 0;
1851         if ( $svcdb eq 'svc_phone' ) {
1852           if ( $part_pkg->plan eq 'voip_inbound' ) {
1853             $hash{'outbound'} = 0;
1854             $hash{'inbound'}  = 1;
1855           } elsif ( $part_pkg->option('selfservice_inbound_format')
1856                 or  $conf->config('selfservice-default_inbound_cdr_format')
1857           ) {
1858             $hash{'inbound'}  = 1;
1859           }
1860         }
1861         foreach (qw(inbound outbound)) {
1862           # hmm...we can't filter by status here, because there might
1863           # not be cdr_terminations at all.  have to go by date.
1864           # find all since the last bill date.
1865           # XXX cdr types?  we are going to need them.
1866           if ( $hash{$_} ) {
1867             my $sum_cdr = $svc_x->sum_cdrs(
1868               'inbound' => ( $_ eq 'inbound' ? 1 : 0 ),
1869               'begin'   => ($cust_pkg->last_bill || 0),
1870               'nonzero' => 1,
1871               'disable_charged_party' => 1,
1872             );
1873             $hash{$_} = $sum_cdr->hashref;
1874           }
1875         }
1876       } # not hiding usage
1877     } # svcdb
1878
1879     push @svcs, \%hash;
1880   } # foreach $cust_svc
1881
1882   foreach my $field (keys %bytes_used_total) {
1883     if ($field =~ /bytes/) {
1884       $bytes_used_total{$field} = display_bytecount($bytes_used_total{$field});
1885     }
1886   }
1887
1888   return { 
1889     'svcnum'   => $session->{'svcnum'},
1890     'custnum'  => $custnum,
1891     'date_format' => $conf->config('date_format') || '%m/%d/%Y',
1892     'view_usage_nodomain' => $conf->exists('selfservice-view_usage_nodomain'),
1893     'svcs'     => \@svcs,
1894     'bytes_used_total' => \%bytes_used_total,
1895     'usage_pools' => [
1896       map { $usage_pools{$_} }
1897       sort { $a cmp $b }
1898       keys %usage_pools
1899     ],
1900     'hide_usage' => $hide_usage,
1901   };
1902
1903 }
1904
1905 sub _customer_svc_x {
1906   my($custnum, $svcnum, $table) = (shift, shift, shift);
1907   my $hashref = ref($svcnum) ? $svcnum : { 'svcnum' => $svcnum };
1908
1909   $custnum =~ /^(\d+)$/ or die "illegal custnum";
1910   my $search = " AND custnum = $1";
1911   #$search .= " AND agentnum = ". $session->{'agentnum'} if $context eq 'agent';
1912
1913   qsearchs( {
1914     'table'     => ($table || 'svc_acct'),
1915     'addl_from' => 'LEFT JOIN cust_svc  USING ( svcnum  ) '.
1916                    'LEFT JOIN cust_pkg  USING ( pkgnum  ) ',#.
1917                    #'LEFT JOIN cust_main USING ( custnum ) ',
1918     'hashref'   => $hashref,
1919     'extra_sql' => $search, #important
1920   } );
1921
1922 }
1923
1924 sub svc_status_html {
1925   my $p = shift;
1926
1927   my($context, $session, $custnum) = _custoragent_session_custnum($p);
1928   return { 'error' => $session } if $context eq 'error';
1929
1930   #XXX only svc_dsl for now
1931   my $svc_x = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_dsl')
1932     or return { 'error' => "Service not found" };
1933
1934   my $html = $svc_x->getstatus_html;
1935
1936   return { 'html' => $html };
1937
1938 }
1939
1940 sub svc_status_hash {
1941   my $p = shift;
1942
1943   my($context, $session, $custnum) = _custoragent_session_custnum($p);
1944   return { 'error' => $session } if $context eq 'error';
1945
1946   #XXX only svc_acct for now
1947   my $svc_x = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_acct')
1948     or return { 'error' => "Service not found" };
1949
1950   my ( $html, $hashref ) = $svc_x->export_getstatus;
1951   return $hashref;
1952
1953 }
1954
1955 sub set_svc_status_hash    { _svc_method_X(shift, 'export_setstatus') }
1956 sub set_svc_status_listadd { _svc_method_X(shift, 'export_setstatus_listadd') }
1957 sub set_svc_status_listdel { _svc_method_X(shift, 'export_setstatus_listdel') }
1958 sub set_svc_status_vacationadd { _svc_method_X(shift, 'export_setstatus_vacationadd') }
1959 sub set_svc_status_vacationdel { _svc_method_X(shift, 'export_setstatus_vacationdel') }
1960
1961 sub _svc_method_X {
1962   my( $p, $method ) = @_;
1963
1964   my($context, $session, $custnum) = _custoragent_session_custnum($p);
1965   return { 'error' => $session } if $context eq 'error';
1966
1967   #XXX only svc_acct for now
1968   my $svc_x = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_acct')
1969     or return { 'error' => "Service not found" };
1970
1971   warn "$method ". join(' / ', map "$_=>".$p->{$_}, keys %$p )
1972     if $DEBUG;
1973   my $error = $svc_x->$method($p); #$p? returns error?
1974   return { 'error' => $error } if $error;
1975
1976   return {}; #? { 'error' => '' }
1977
1978 }
1979
1980 sub acct_forward_info {
1981   my $p = shift;
1982
1983   my($context, $session, $custnum) = _custoragent_session_custnum($p);
1984   return { 'error' => $session } if $context eq 'error';
1985
1986   my $svc_forward = _customer_svc_x( $custnum,
1987                                      { 'srcsvc' => $p->{'svcnum'} },
1988                                      'svc_forward',
1989                                    )
1990     or return { 'error' => '',
1991                 'dst'   => '',
1992               };
1993
1994   return { 'error' => '',
1995            'dst'   => $svc_forward->dst || $svc_forward->dstsvc_acct->email,
1996          };
1997
1998 }
1999
2000 sub process_acct_forward {
2001   my $p = shift;
2002   my($context, $session, $custnum) = _custoragent_session_custnum($p);
2003   return { 'error' => $session } if $context eq 'error';
2004
2005   my $old = _customer_svc_x( $custnum,
2006                              { 'srcsvc' => $p->{'svcnum'} },
2007                              'svc_forward',
2008                            );
2009
2010   if ( $p->{'dst'} eq '' ) {
2011     if ( $old ) {
2012       my $error = $old->delete;
2013       return { 'error' => $error };
2014     }
2015     return { 'error' => '' };
2016   }
2017
2018   my $new = new FS::svc_forward { 'srcsvc' => $p->{'svcnum'},
2019                                   'dst'    => $p->{'dst'},
2020                                 };
2021
2022   my $error;
2023   if ( $old ) {
2024     $new->svcnum($old->svcnum);
2025     my $cust_svc = $old->cust_svc;
2026     $new->svcpart($old->svcpart);
2027     $new->pkgnuym($old->pkgnum);
2028     $error = $new->replace($old);
2029   } else {
2030     my $conf = new FS::Conf;
2031     $new->svcpart($conf->config('selfservice-svc_forward_svcpart'));
2032
2033     my $svc_acct = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_acct' )
2034       or return { 'error' => 'No service' }; #how would we even get here?
2035
2036     $new->pkgnum( $svc_acct->cust_svc->pkgnum );
2037
2038     $error = $new->insert;
2039   }
2040
2041   return { 'error' => $error };
2042
2043 }
2044
2045 sub list_dsl_devices {
2046   my $p = shift;
2047
2048   my($context, $session, $custnum) = _custoragent_session_custnum($p);
2049   return { 'error' => $session } if $context eq 'error';
2050
2051   my $svc_dsl = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_dsl' )
2052     or return { 'error' => "Service not found" };
2053
2054   return {
2055     'devices' => [ map {
2056                          +{ 'mac_addr' => $_->mac_addr };
2057                        } $svc_dsl->dsl_device
2058                  ],
2059   };
2060
2061 }
2062
2063 sub add_dsl_device {
2064   my $p = shift;
2065
2066   my($context, $session, $custnum) = _custoragent_session_custnum($p);
2067   return { 'error' => $session } if $context eq 'error';
2068
2069   my $svc_dsl = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_dsl' )
2070     or return { 'error' => "Service not found" };
2071
2072   return { 'error' => 'No MAC address supplied' }
2073     unless length($p->{'mac_addr'});
2074
2075   my $dsl_device = new FS::dsl_device { 'svcnum'   => $svc_dsl->svcnum,
2076                                         'mac_addr' => scalar($p->{'mac_addr'}),
2077                                       };
2078   my $error = $dsl_device->insert;
2079   return { 'error' => $error };
2080
2081 }
2082
2083 sub delete_dsl_device {
2084   my $p = shift;
2085
2086   my($context, $session, $custnum) = _custoragent_session_custnum($p);
2087   return { 'error' => $session } if $context eq 'error';
2088
2089   my $svc_dsl = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_dsl' )
2090     or return { 'error' => "Service not found" };
2091
2092   my $dsl_device = qsearchs('dsl_device', { 'svcnum'   => $svc_dsl->svcnum,
2093                                             'mac_addr' => scalar($p->{'mac_addr'}),
2094                                           }
2095                            )
2096     or return { 'error' => 'Unknown MAC address: '. $p->{'mac_addr'} };
2097
2098   my $error = $dsl_device->delete;
2099   return { 'error' => $error };
2100
2101 }
2102
2103 sub port_graph {
2104   my $p = shift;
2105   _usage_details( \&_port_graph, $p,
2106                   'svcdb' => 'svc_port',
2107                 );
2108 }
2109
2110 sub _port_graph {
2111   my($svc_port, $begin, $end) = @_;
2112   my @usage = ();
2113   my $pngOrError = $svc_port->graph_png( start=>$begin, end=> $end );
2114   push @usage, { 'png' => $pngOrError };
2115   (@usage);
2116 }
2117
2118 sub _list_svc_usage {
2119   my($svc_acct, $begin, $end) = @_;
2120   my @usage = ();
2121   foreach my $part_export ( 
2122     map { qsearch ( 'part_export', { 'exporttype' => $_ } ) }
2123     qw( sqlradius sqlradius_withdomain )
2124   ) {
2125     push @usage, @ { $part_export->usage_sessions($begin, $end, $svc_acct) };
2126   }
2127   (@usage);
2128 }
2129
2130 sub list_svc_usage {
2131   _usage_details(\&_list_svc_usage, @_);
2132 }
2133
2134 sub _list_support_usage {
2135   my($svc_acct, $begin, $end) = @_;
2136   my @usage = ();
2137   foreach ( grep { $begin <= $_->_date && $_->_date <= $end }
2138             qsearch('acct_rt_transaction', { 'svcnum' => $svc_acct->svcnum })
2139           ) {
2140     push @usage, { 'seconds'  => $_->seconds,
2141                    'support'  => $_->support,
2142                    '_date'    => $_->_date,
2143                    'id'       => $_->transaction_id,
2144                    'creator'  => $_->creator,
2145                    'subject'  => $_->subject,
2146                    'status'   => $_->status,
2147                    'ticketid' => $_->ticketid,
2148                  };
2149   }
2150   (@usage);
2151 }
2152
2153 sub list_support_usage {
2154   _usage_details(\&_list_support_usage, @_);
2155 }
2156
2157 sub _list_cdr_usage {
2158   # XXX CDR type support...
2159   # XXX any way to do a paged search on this?
2160   # we have to return the results all at once...
2161   my($svc_x, $begin, $end, %opt) = @_;
2162   map [ $_->downstream_csv(%opt, 'keeparray' => 1) ],
2163     $svc_x->get_cdrs(
2164       'begin' => $begin,
2165       'end'   => $end,
2166       'disable_charged_party' => 1,
2167       %opt
2168     );
2169 }
2170
2171 sub list_cdr_usage {
2172   my $p = shift;
2173   _usage_details( \&_list_cdr_usage, $p );
2174 }
2175
2176 sub _usage_details {
2177   my($callback, $p, %opt) = @_;
2178   my $conf = FS::Conf->new;
2179
2180   if ( $conf->exists('selfservice_hide-usage') ) {
2181     return { 'error' => 'Viewing usage is not allowed.' };
2182   }
2183
2184   my($context, $session, $custnum) = _custoragent_session_custnum($p);
2185   return { 'error' => $session } if $context eq 'error';
2186
2187   my $search = { 'svcnum' => $p->{'svcnum'} };
2188   $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2189
2190   my $cust_svc = qsearchs( 'cust_svc', $search );
2191   return { 'error' => 'No service selected in list_svc_usage' } 
2192     unless $cust_svc;
2193
2194   my $svc_x = $cust_svc->svc_x;
2195   my $svcdb = $svc_x->table;
2196   my $cust_pkg = $cust_svc->cust_pkg;
2197   my $freq     = $cust_pkg->part_pkg->freq;
2198   my %callback_opt;
2199   my $header = [];
2200   if ( $svcdb eq 'svc_phone' or $svcdb eq 'svc_pbx' ) {
2201     my $format = '';
2202     if ( $p->{inbound} ) {
2203       $format = $cust_pkg->part_pkg->option('selfservice_inbound_format') 
2204                 || $conf->config('selfservice-default_inbound_cdr_format')
2205                 || 'source_default';
2206       $callback_opt{inbound} = 1;
2207     } else {
2208       $format = $cust_pkg->part_pkg->option('selfservice_format')
2209                 || $conf->config('selfservice-default_cdr_format')
2210                 || 'default';
2211     }
2212
2213     $callback_opt{format} = $format;
2214     $callback_opt{use_clid} = 1;
2215     $header = [ split(',', FS::cdr::invoice_header($format) ) ];
2216   }
2217
2218   my $start    = $cust_pkg->setup;
2219   #my $end      = $cust_pkg->bill; # or time?
2220   my $end      = time;
2221
2222   unless ( $p->{beginning} ) {
2223     $p->{beginning} = $cust_pkg->last_bill;
2224     $p->{ending}    = $end;
2225   }
2226
2227   die "illegal beginning" if $p->{beginning} !~ /^\d*$/;
2228   die "illegal ending"    if $p->{ending}    !~ /^\d*$/;
2229
2230   my (@usage) = &$callback($svc_x, $p->{beginning}, $p->{ending}, 
2231     %callback_opt
2232   );
2233
2234   if ( $conf->exists('selfservice-hide_cdr_price') ) {
2235     # ugly kludge, I know
2236     my ($delete_col) = grep { $header->[$_] eq 'Price' } (0..scalar(@$header));
2237     if (defined $delete_col) {
2238       delete($_->[$delete_col]) foreach ($header, @usage);
2239     }
2240   }
2241
2242   #kinda false laziness with FS::cust_main::bill, but perhaps
2243   #we should really change this bit to DateTime and DateTime::Duration
2244   #
2245   #change this bit to use Date::Manip? CAREFUL with timezones (see
2246   # mailing list archive)
2247   my ($nsec,$nmin,$nhour,$nmday,$nmon,$nyear) =
2248     (localtime($p->{ending}) )[0,1,2,3,4,5];
2249   my ($psec,$pmin,$phour,$pmday,$pmon,$pyear) =
2250     (localtime($p->{beginning}) )[0,1,2,3,4,5];
2251
2252   if ( $freq =~ /^\d+$/ ) {
2253     $nmon += $freq;
2254     until ( $nmon < 12 ) { $nmon -= 12; $nyear++; }
2255     $pmon -= $freq;
2256     until ( $pmon >= 0 ) { $pmon += 12; $pyear--; }
2257   } elsif ( $freq =~ /^(\d+)w$/ ) {
2258     my $weeks = $1;
2259     $nmday += $weeks * 7;
2260     $pmday -= $weeks * 7;
2261   } elsif ( $freq =~ /^(\d+)d$/ ) {
2262     my $days = $1;
2263     $nmday += $days;
2264     $pmday -= $days;
2265   } elsif ( $freq =~ /^(\d+)h$/ ) {
2266     my $hours = $1;
2267     $nhour += $hours;
2268     $phour -= $hours;
2269   } else {
2270     return { 'error' => "unparsable frequency: ". $freq };
2271   }
2272   
2273   my $previous  = timelocal_nocheck($psec,$pmin,$phour,$pmday,$pmon,$pyear);
2274   my $next      = timelocal_nocheck($nsec,$nmin,$nhour,$nmday,$nmon,$nyear);
2275
2276   { 
2277     'error'     => '',
2278     'svcnum'    => $p->{svcnum},
2279     'beginning' => $p->{beginning},
2280     'ending'    => $p->{ending},
2281     'inbound'   => $p->{inbound},
2282     'previous'  => ($previous > $start) ? $previous : $start,
2283     'next'      => ($next < $end) ? $next : $end,
2284     'header'    => $header,
2285     'usage'     => \@usage,
2286   };
2287 }
2288
2289 sub order_pkg {
2290   my $p = shift;
2291
2292   my($context, $session, $custnum) = _custoragent_session_custnum($p);
2293   return { 'error' => $session } if $context eq 'error';
2294
2295   my $search = { 'custnum' => $custnum };
2296   $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2297   my $cust_main = qsearchs('cust_main', $search )
2298     or return { 'error' => "unknown custnum $custnum" };
2299
2300   my $status = $cust_main->status;
2301
2302   my %order_pkg_options = ();
2303   if ( $p->{locationnum} > 0 ) {
2304     $order_pkg_options{locationnum} = delete($p->{locationnum});
2305   } elsif ( $p->{address1} ) {
2306     $order_pkg_options{'cust_location'} = new FS::cust_location {
2307       map { $_ => $p->{$_} }
2308         qw( address1 address2 city county state zip country )
2309     };
2310   }
2311
2312   #false laziness w/ClientAPI/Signup.pm
2313
2314   my $cust_pkg = new FS::cust_pkg ( {
2315     'custnum'  => $custnum,
2316     'pkgpart'  => $p->{'pkgpart'},
2317     'quantity' => $p->{'quantity'} || 1,
2318   } );
2319   my $error = $cust_pkg->check;
2320   return { 'error' => $error } if $error;
2321
2322   my @svc = ();
2323   unless ( $p->{'svcpart'} eq 'none' ) {
2324
2325     my $svcdb;
2326     my $svcpart = '';
2327     if ( $p->{'svcpart'} =~ /^(\d+)$/ ) {
2328       $svcpart = $1;
2329       my $part_svc = qsearchs('part_svc', { 'svcpart' => $svcpart } );
2330       return { 'error' => "Unknown svcpart $svcpart" } unless $part_svc;
2331       $svcdb = $part_svc->svcdb;
2332     } else {
2333       $svcdb = 'svc_acct';
2334     }
2335     $svcpart ||= $cust_pkg->part_pkg->svcpart($svcdb);
2336
2337     my %fields = (
2338       'svc_acct'     => [ qw( username domsvc _password sec_phrase popnum ) ],
2339       'svc_domain'   => [ qw( domain ) ],
2340       'svc_phone'    => [ qw( phonenum pin sip_password phone_name ) ],
2341       'svc_external' => [ qw( id title ) ],
2342       'svc_pbx'      => [ qw( id title ) ],
2343     );
2344   
2345     my $svc_x = "FS::$svcdb"->new( {
2346       'svcpart'   => $svcpart,
2347       map { $_ => $p->{$_} } @{$fields{$svcdb}}
2348     } );
2349     
2350     if ( $svcdb eq 'svc_acct' && exists($p->{"snarf_machine1"}) ) {
2351       my @acct_snarf;
2352       my $snarfnum = 1;
2353       while ( length($p->{"snarf_machine$snarfnum"}) ) {
2354         my $acct_snarf = new FS::acct_snarf ( {
2355           'machine'   => $p->{"snarf_machine$snarfnum"},
2356           'protocol'  => $p->{"snarf_protocol$snarfnum"},
2357           'username'  => $p->{"snarf_username$snarfnum"},
2358           '_password' => $p->{"snarf_password$snarfnum"},
2359         } );
2360         $snarfnum++;
2361         push @acct_snarf, $acct_snarf;
2362       }
2363       $svc_x->child_objects( \@acct_snarf );
2364     }
2365     
2366     my $y = $svc_x->setdefault; # arguably should be in new method
2367     return { 'error' => $y } if $y && !ref($y);
2368   
2369     $error = $svc_x->check;
2370     return { 'error' => $error } if $error;
2371
2372     push @svc, $svc_x;
2373
2374   }
2375
2376   $error = $cust_main->order_pkg(
2377     'cust_pkg' => $cust_pkg,
2378     'svcs'     => \@svc,
2379     'noexport' => 1,
2380     %order_pkg_options,
2381   );
2382   return { 'error' => $error } if $error;
2383
2384   my $conf = new FS::Conf;
2385   if ( $conf->exists('signup_server-realtime') ) {
2386
2387     my $bill_error = _do_bop_realtime( $cust_main, $status, 'collect'=>$p->{run_bill_events} );
2388
2389     if ($bill_error) {
2390       $cust_pkg->cancel('quiet'=>1);
2391       return $bill_error;
2392     } else {
2393       $cust_pkg->reexport;
2394     }
2395
2396   } else {
2397     $cust_pkg->reexport;
2398   }
2399
2400   my $svcnum = $svc[0] ? $svc[0]->svcnum : '';
2401
2402   return { error=>'', pkgnum=>$cust_pkg->pkgnum, svcnum=>$svcnum };
2403
2404 }
2405
2406 sub change_pkg {
2407   my $p = shift;
2408
2409   my($context, $session, $custnum) = _custoragent_session_custnum($p);
2410   return { 'error' => $session } if $context eq 'error';
2411
2412   my $conf = new FS::Conf;
2413   my $immutable = $conf->exists('selfservice_immutable-package');
2414   return { 'error' => "Package modification disabled" } if $immutable;
2415
2416   my $search = { 'custnum' => $custnum };
2417   $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2418   my $cust_main = qsearchs('cust_main', $search )
2419     or return { 'error' => "unknown custnum $custnum" };
2420
2421   my $status = $cust_main->status;
2422   my $cust_pkg = qsearchs('cust_pkg', { 'pkgnum' => $p->{pkgnum} } )
2423     or return { 'error' => "unknown package $p->{pkgnum}" };
2424
2425   #if someone does need self-service package change of suspended packages,
2426   # figure out how to be more discriminating
2427   return { error=>"Can't change a suspended package", pkgnum=>$cust_pkg->pkgnum}
2428     if $cust_pkg->status eq 'suspended';
2429
2430   my $err_or_cust_pkg = $cust_pkg->change( 'pkgpart'  => $p->{'pkgpart'},
2431                                            'quantity' => $p->{'quantity'} || 1,
2432                                          );
2433
2434   return { error=>$err_or_cust_pkg, pkgnum=>$cust_pkg->pkgnum }
2435     unless ref($err_or_cust_pkg);
2436
2437   if ( $conf->exists('signup_server-realtime') ) {
2438
2439     my $bill_error = _do_bop_realtime( $cust_main, $status, 'no_invoice_void'=>1 );
2440
2441     if ($bill_error) {
2442       $err_or_cust_pkg->suspend;
2443       return $bill_error;
2444     } else {
2445       $err_or_cust_pkg->reexport;
2446     }
2447
2448   } else {  
2449     $err_or_cust_pkg->reexport;
2450   }
2451
2452   return { error => '', pkgnum => $cust_pkg->pkgnum };
2453
2454 }
2455
2456 sub order_recharge {
2457   my $p = shift;
2458
2459   my($context, $session, $custnum) = _custoragent_session_custnum($p);
2460   return { 'error' => $session } if $context eq 'error';
2461
2462   my $search = { 'custnum' => $custnum };
2463   $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2464   my $cust_main = qsearchs('cust_main', $search )
2465     or return { 'error' => "unknown custnum $custnum" };
2466
2467   my $status = $cust_main->status;
2468   my $cust_svc = qsearchs( 'cust_svc', { 'svcnum' => $p->{'svcnum'} } )
2469     or return { 'error' => "unknown service " . $p->{'svcnum'} };
2470
2471   my $svc_x = $cust_svc->svc_x;
2472   my $part_pkg = $cust_svc->cust_pkg->part_pkg;
2473
2474   my %vhash =
2475     map { $_ =~ /^recharge_(.*)$/; $1, $part_pkg->option($_, 1) } 
2476     qw ( recharge_seconds recharge_upbytes recharge_downbytes
2477          recharge_totalbytes );
2478   my $amount = $part_pkg->option('recharge_amount', 1); 
2479   
2480   my ($l, $v, $d) = $cust_svc->label;  # blah
2481   my $pkg = "Recharge $v"; 
2482
2483   my $bill_error = $cust_main->charge($amount, $pkg,
2484      "time: $vhash{seconds}, up: $vhash{upbytes}," . 
2485      "down: $vhash{downbytes}, total: $vhash{totalbytes}",
2486      $part_pkg->taxclass); #meh
2487
2488   my $conf = new FS::Conf;
2489   if ( $conf->exists('signup_server-realtime') && !$bill_error ) {
2490
2491     $bill_error = _do_bop_realtime( $cust_main, $status );
2492
2493     if ($bill_error) {
2494       return $bill_error;
2495     } else {
2496       my $error = $svc_x->recharge (\%vhash);
2497       return { 'error' => $error } if $error;
2498     }
2499
2500   } else {  
2501     my $error = $bill_error;
2502     $error ||= $svc_x->recharge (\%vhash);
2503     return { 'error' => $error } if $error;
2504   }
2505
2506   return { error => '', svc => $cust_svc->part_svc->svc };
2507
2508 }
2509
2510 sub _do_bop_realtime {
2511   my ($cust_main, $status, %opt) = @_;
2512
2513   my $old_balance = $cust_main->balance;
2514
2515   my @cust_bill;
2516   my $bill_error = $cust_main->bill(
2517     'return_bill'   => \@cust_bill,
2518   );
2519
2520   $bill_error ||= $cust_main->apply_payments_and_credits;
2521
2522   $bill_error ||= $cust_main->realtime_collect('selfservice' => 1)
2523     if $cust_main->payby =~ /^(CARD|CHEK)$/;
2524
2525   if (    $cust_main->balance > $old_balance
2526        && $cust_main->balance > 0
2527        && ( $cust_main->payby !~ /^(BILL|DCRD|DCHK)$/
2528               || $status eq 'suspended'
2529           )
2530      )
2531   {
2532     unless ( $opt{'no_invoice_void'} ) {
2533
2534       #this used to apply a credit, but now we can void invoices...
2535       foreach my $cust_bill (@cust_bill) {
2536         my $voiderror = $cust_bill->void('automatic payment failed');
2537         warn "Error voiding cust bill after decline: $voiderror" if $voiderror;
2538       }
2539
2540     }
2541
2542     return { 'error' => '_decline', 'bill_error' => $bill_error };
2543   }
2544
2545   if ( $opt{'collect'} ) {
2546     my $collect_error = $cust_main->collect();
2547     return { 'error' => '_decline', 'bill_error' => $collect_error }
2548      if $collect_error; #?
2549   }
2550
2551   '';
2552 }
2553
2554 sub renew_info {
2555   my $p = shift;
2556
2557   my($context, $session, $custnum) = _custoragent_session_custnum($p);
2558   return { 'error' => $session } if $context eq 'error';
2559
2560   my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
2561     or return { 'error' => "unknown custnum $custnum" };
2562
2563   my @cust_pkg = sort { $a->bill <=> $b->bill }
2564                  grep { $_->part_pkg->freq ne '0' }
2565                  $cust_main->ncancelled_pkgs;
2566
2567   #return { 'error' => 'No active packages to renew.' } unless @cust_pkg;
2568
2569   my $total = $cust_main->balance;
2570
2571   my @array = map {
2572                     my $bill = $_->bill;
2573                     $total += $_->part_pkg->base_recur($_, \$bill);
2574                     my $renew_date = $_->part_pkg->add_freq($_->bill);
2575                     {
2576                       'pkgnum'             => $_->pkgnum,
2577                       'amount'             => sprintf('%.2f', $total),
2578                       'bill_date'          => $_->bill,
2579                       'bill_date_pretty'   => time2str('%x', $_->bill),
2580                       'renew_date'         => $renew_date,
2581                       'renew_date_pretty'  => time2str('%x', $renew_date),
2582                       'expire_date'        => $_->expire,
2583                       'expire_date_pretty' => time2str('%x', $_->expire),
2584                     };
2585                   }
2586                   @cust_pkg;
2587
2588   return { 'dates' => \@array };
2589
2590 }
2591
2592 sub payment_info_renew_info {
2593   my $p = shift;
2594   my $renew_info   = renew_info($p);
2595   my $payment_info = payment_info($p);
2596   return { %$renew_info,
2597            %$payment_info,
2598          };
2599 }
2600
2601 sub order_renew {
2602   my $p = shift;
2603
2604   my($context, $session, $custnum) = _custoragent_session_custnum($p);
2605   return { 'error' => $session } if $context eq 'error';
2606
2607   my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
2608     or return { 'error' => "unknown custnum $custnum" };
2609
2610   my $date = $p->{'date'};
2611
2612   my $now = time;
2613
2614   #freeside-daily -n -d $date fs_daily $custnum
2615   $cust_main->bill_and_collect( 'time'         => $date,
2616                                 'invoice_time' => $now,
2617                                 'actual_time'  => $now,
2618                                 'check_freq'   => '1d',
2619                               );
2620
2621   return { 'error' => '' };
2622
2623 }
2624
2625 sub suspend_pkg {
2626   my $p = shift;
2627   my $session = _cache->get($p->{'session_id'})
2628     or return { 'error' => "Can't resume session" }; #better error message
2629
2630   my $custnum = $session->{'custnum'};
2631
2632   my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
2633     or return { 'error' => "unknown custnum $custnum" };
2634
2635   my $conf = new FS::Conf;
2636   my $reasonnum = 
2637     $conf->config('selfservice-self_suspend_reason', $cust_main->agentnum)
2638       or return { 'error' => 'Permission denied' };
2639
2640   my $pkgnum = $p->{'pkgnum'};
2641
2642   my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
2643                                         'pkgnum'  => $pkgnum,   } )
2644     or return { 'error' => "unknown pkgnum $pkgnum" };
2645
2646   my $error = $cust_pkg->suspend(reason => $reasonnum);
2647   return { 'error' => $error };
2648
2649 }
2650
2651 sub cancel_pkg {
2652   my $p = shift;
2653   my $session = _cache->get($p->{'session_id'})
2654     or return { 'error' => "Can't resume session" }; #better error message
2655
2656   my $custnum = $session->{'custnum'};
2657   my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
2658     or return { 'error' => "unknown custnum $custnum" };
2659
2660   my $pkgnum = $p->{'pkgnum'};
2661   my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
2662                                         'pkgnum'  => $pkgnum,   } )
2663     or return { 'error' => "unknown pkgnum $pkgnum" };
2664
2665   my $error = $cust_pkg->cancel( 'quiet' => 1,
2666                                  'date'  => $p->{'date'},
2667                                );
2668   return { 'error' => $error };
2669 }
2670
2671 sub provision_phone {
2672   my $p = shift;
2673   my @bulkdid;
2674   @bulkdid = @{$p->{'bulkdid'}} if $p->{'bulkdid'};
2675
2676   #editing an existing phone number
2677   if ( $p->{'svcnum'} && $p->{'svcnum'} =~ /^\d+$/ ) {
2678       my($context, $session, $custnum) = _custoragent_session_custnum($p);
2679       return { 'error' => $session } if $context eq 'error';
2680     
2681       my $svc_phone = qsearchs('svc_phone', { svcnum => $p->{'svcnum'} });
2682       return { 'error' => 'service not found' } unless $svc_phone;
2683       return { 'error' => 'invalid svcnum' } 
2684         if $svc_phone && $svc_phone->cust_svc->cust_pkg->custnum != $custnum;
2685
2686       $svc_phone->email($p->{'email'}) 
2687         if $svc_phone->email ne $p->{'email'} && $p->{'email'} =~ /^([\w\.\d@]+|)$/;
2688       $svc_phone->forwarddst($p->{'forwarddst'}) 
2689         if $svc_phone->forwarddst ne $p->{'forwarddst'} 
2690             && $p->{'forwarddst'} =~ /^(\d+|)$/;
2691       return { 'error' => $svc_phone->replace };
2692  }
2693
2694   # single DID LNP
2695   unless ( $p->{'lnp'} ) {
2696     $p->{'lnp_desired_due_date'} = parse_datetime($p->{'lnp_desired_due_date'});
2697     $p->{'lnp_status'} = "portingin";
2698     return _provision( 'FS::svc_phone',
2699                   [qw(lnp_desired_due_date lnp_other_provider 
2700                     lnp_other_provider_account phonenum countrycode lnp_status)],
2701                   [qw(phonenum countrycode)],
2702                   $p,
2703                   @_
2704                 );
2705   }
2706
2707   # single DID order (the usual case)
2708   unless (scalar(@bulkdid)) {
2709     return _provision( 'FS::svc_phone',
2710                   [qw(phonenum countrycode)],
2711                   [qw(phonenum countrycode)],
2712                   $p,
2713                   @_
2714                 );
2715   }
2716
2717   # bulk DID order case
2718   my $error;
2719   foreach my $did ( @bulkdid ) {
2720     $did =~ s/[^0-9]//g;
2721     $error = _provision( 'FS::svc_phone',
2722               [qw(phonenum countrycode)],
2723               [qw(phonenum countrycode)],
2724               {
2725                 'pkgnum' => $p->{'pkgnum'},
2726                 'svcpart' => $p->{'svcpart'},
2727                 'phonenum' => $did,
2728                 'countrycode' => $p->{'countrycode'},
2729                 'session_id' => $p->{'session_id'},
2730               }
2731             );
2732     return $error if ($error->{'error'} && length($error->{'error'}) > 1);
2733   }
2734   { 'bulkdid' => [ @bulkdid ], 'svc' => $error->{'svc'} }
2735 }
2736
2737 sub provision_pbx {
2738   my $p = shift;
2739   warn "provision_pbx called\n"
2740     if $DEBUG;
2741
2742   warn "provision_pbx calling _provision\n"
2743     if $DEBUG;
2744   _provision( 'FS::svc_pbx',
2745               [qw(id title max_extensions max_simultaneous ip_addr)],
2746               [qw(id title max_extensions max_simultaneous ip_addr)],
2747               $p,
2748               @_
2749             );
2750 }
2751
2752 sub provision_acct {
2753   my $p = shift;
2754   warn "provision_acct called\n"
2755     if $DEBUG;
2756
2757   return { 'error' => gettext('passwords_dont_match') }
2758     if $p->{'_password'} ne $p->{'_password2'};
2759   return { 'error' => gettext('empty_password') }
2760     unless length($p->{'_password'});
2761  
2762   if ($p->{'domsvc'}) {
2763     my %domains = domain_select_hash FS::svc_acct(map { $_ => $p->{$_} }
2764                                                   qw ( svcpart pkgnum ) );
2765     return { 'error' => gettext('invalid_domain') }
2766       unless ($domains{$p->{'domsvc'}});
2767   }
2768
2769   warn "provision_acct calling _provision\n"
2770     if $DEBUG;
2771   _provision( 'FS::svc_acct',
2772               [qw(username _password domsvc)],
2773               [qw(username _password domsvc)],
2774               $p,
2775               @_
2776             );
2777 }
2778
2779 sub provision_external {
2780   my $p = shift;
2781   #_provision( 'FS::svc_external', [qw(id title)], [qw(id title)], $p, @_ );
2782   _provision( 'FS::svc_external',
2783               [],
2784               [qw(id title)],
2785               $p,
2786               @_
2787             );
2788 }
2789
2790 sub provision_forward {
2791   my $p = shift;
2792   _provision( 'FS::svc_forward',
2793               ['srcsvc','src','dstsvc','dst'],
2794               [],
2795               $p,
2796             );
2797 }
2798
2799 sub _provision {
2800   my( $class, $fields, $return_fields, $p ) = splice(@_, 0, 4);
2801   warn "_provision called for $class\n"
2802     if $DEBUG;
2803
2804   my($context, $session, $custnum) = _custoragent_session_custnum($p);
2805   return { 'error' => $session } if $context eq 'error';
2806
2807   my $search = { 'custnum' => $custnum };
2808   $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2809   my $cust_main = qsearchs('cust_main', $search )
2810     or return { 'error' => "unknown custnum $custnum" };
2811
2812   my $pkgnum = $p->{'pkgnum'};
2813
2814   warn "searching for custnum $custnum pkgnum $pkgnum\n"
2815     if $DEBUG;
2816   my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
2817                                         'pkgnum'  => $pkgnum,
2818                                                                } )
2819     or return { 'error' => "unknown pkgnum $pkgnum" };
2820
2821   warn "searching for svcpart ". $p->{'svcpart'}. "\n"
2822     if $DEBUG;
2823   my $part_svc = qsearchs('part_svc', { 'svcpart' => $p->{'svcpart'} } )
2824     or return { 'error' => "unknown svcpart $p->{'svcpart'}" };
2825
2826   return { error=> 'svcpart '. $p->{'svcpart'}. " is not a $class definition" }
2827     if $class ne 'FS::'. $part_svc->svcdb;
2828
2829   warn "creating $class record\n"
2830     if $DEBUG;
2831   my $svc_x = $class->new( {
2832     'pkgnum'  => $p->{'pkgnum'},
2833     'svcpart' => $p->{'svcpart'},
2834     map { $_ => $p->{$_} } @$fields
2835   } );
2836
2837   my %insert_args = ();
2838   #i shouldn't be a special case here (pass an option or something)
2839   if ( $class eq 'FS::svc_phone'
2840          && grep length($p->{$_}), @location_editable_fields
2841      )
2842   {
2843     $insert_args{'cust_location'} = new FS::cust_location {
2844       map { $_ => $p->{$_} } @location_editable_fields
2845     };
2846   }
2847
2848   warn "inserting $class record\n"
2849     if $DEBUG;
2850   my $error = $svc_x->insert(%insert_args);
2851
2852   unless ( $error ) {
2853     warn "finding inserted record for svcnum ". $svc_x->svcnum. "\n"
2854       if $DEBUG;
2855     $svc_x = qsearchs($svc_x->table, { 'svcnum' => $svc_x->svcnum })
2856   }
2857
2858   my $return = { 'svc'   => $part_svc->svc,
2859                  'error' => $error,
2860                  map { $_ => $svc_x->get($_) } @$return_fields
2861                };
2862   warn "_provision returning ". Dumper($return). "\n"
2863     if $DEBUG;
2864   return $return;
2865
2866 }
2867
2868 sub part_svc_info {
2869   my $p = shift;
2870
2871   my($context, $session, $custnum) = _custoragent_session_custnum($p);
2872   return { 'error' => $session } if $context eq 'error';
2873
2874   my $search = { 'custnum' => $custnum };
2875   $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2876   my $cust_main = qsearchs('cust_main', $search )
2877     or return { 'error' => "unknown custnum $custnum" };
2878
2879   my $pkgnum = $p->{'pkgnum'};
2880
2881   my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
2882                                         'pkgnum'  => $pkgnum,
2883                                                                } )
2884     or return { 'error' => "unknown pkgnum $pkgnum" };
2885
2886   my $svcpart = $p->{'svcpart'};
2887
2888   my $pkg_svc = qsearchs('pkg_svc', { 'pkgpart' => $cust_pkg->pkgpart,
2889                                       'svcpart' => $svcpart,           } )
2890     or return { 'error' => "unknown svcpart $svcpart for pkgnum $pkgnum" };
2891   my $part_svc = $pkg_svc->part_svc;
2892
2893   my $conf = new FS::Conf;
2894
2895   my $ret = {
2896     'svc'     => $part_svc->svc,
2897     'svcdb'   => $part_svc->svcdb,
2898     'pkgnum'  => $pkgnum,
2899     'svcpart' => $svcpart,
2900     'custnum' => $custnum,
2901
2902     'security_phrase' => 0, #XXX !
2903     'svc_acct_pop'    => [], #XXX !
2904     'popnum'          => '',
2905     'init_popstate'   => '',
2906     'popac'           => '',
2907     'acstate'         => '',
2908
2909     'small_custview' =>
2910       small_custview( $cust_main, $conf->config('countrydefault') ),
2911
2912   };
2913
2914   if ($p->{'svcnum'} && $p->{'svcnum'} =~ /^\d+$/ 
2915                      && $ret->{'svcdb'} eq 'svc_phone') {
2916         $ret->{'svcnum'} = $p->{'svcnum'};
2917         my $svc_phone = qsearchs('svc_phone', { svcnum => $p->{'svcnum'} });
2918         if ( $svc_phone && $svc_phone->cust_svc->cust_pkg->custnum == $custnum ) {
2919             $ret->{'email'} = $svc_phone->email;
2920             $ret->{'forwarddst'} = $svc_phone->forwarddst;
2921         }
2922   }
2923
2924   if ($ret->{'svcdb'} eq 'svc_forward') {
2925     $ret->{'forward_emails'} = {$cust_pkg->forward_emails()};
2926   }
2927
2928   $ret;
2929 }
2930
2931 sub unprovision_svc {
2932   my $p = shift;
2933
2934   my($context, $session, $custnum) = _custoragent_session_custnum($p);
2935   return { 'error' => $session } if $context eq 'error';
2936
2937   my $search = { 'custnum' => $custnum };
2938   $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2939   my $cust_main = qsearchs('cust_main', $search )
2940     or return { 'error' => "unknown custnum $custnum" };
2941
2942   my $svcnum = $p->{'svcnum'};
2943
2944   my $cust_svc = qsearchs('cust_svc', { 'svcnum'  => $svcnum, } )
2945     or return { 'error' => "unknown svcnum $svcnum" };
2946
2947   return { 'error' => "Service $svcnum does not belong to customer $custnum" }
2948     unless $cust_svc->cust_pkg->custnum == $custnum;
2949
2950   my $conf = new FS::Conf;
2951
2952   return { 'svc'   => $cust_svc->part_svc->svc,
2953            'error' => $cust_svc->cancel,
2954            'small_custview' =>
2955              small_custview( $cust_main, $conf->config('countrydefault') ),
2956          };
2957
2958 }
2959
2960 sub myaccount_passwd {
2961   my $p = shift;
2962   my($context, $session, $custnum) = _custoragent_session_custnum($p);
2963   return { 'error' => $session } if $context eq 'error';
2964
2965   return { 'error' => "New passwords don't match." }
2966     if $p->{'new_password'} ne $p->{'new_password2'};
2967
2968   return { 'error' => 'Enter new password' }
2969     unless length($p->{'new_password'});
2970
2971   #my $search = { 'custnum' => $custnum };
2972   #$search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2973   $custnum =~ /^(\d+)$/ or die "illegal custnum";
2974   my $search = " AND custnum = $1";
2975   $search .= " AND agentnum = ". $session->{'agentnum'} if $context eq 'agent';
2976
2977   my $svc_acct = qsearchs( {
2978     'table'     => 'svc_acct',
2979     'addl_from' => 'LEFT JOIN cust_svc  USING ( svcnum  ) '.
2980                    'LEFT JOIN cust_pkg  USING ( pkgnum  ) '.
2981                    'LEFT JOIN cust_main USING ( custnum ) ',
2982     'hashref'   => { 'svcnum' => $p->{'svcnum'}, },
2983     'extra_sql' => $search, #important
2984   } )
2985     or return { 'error' => "Service not found" };
2986
2987   my $error = '';
2988
2989   my $conf = new FS::Conf;
2990
2991   return { 'error' => 'Incorrect current password.' }
2992     if  ( exists($p->{'old_password'})
2993           || $conf->exists('selfservice-password_change_oldpass')
2994         )
2995     && ! $svc_acct->check_password($p->{'old_password'});
2996
2997   $error ||= $svc_acct->is_password_allowed($p->{'new_password'})
2998          ||  $svc_acct->set_password($p->{'new_password'})
2999          ||  $svc_acct->replace();
3000
3001   #regular pw change in self-service should change contact pw too, otherwise its
3002   #way too confusing.  hell its confusing they're separate at all, but alas.
3003   #need to support the "ISP provides email that's used as a contact email" case
3004   #as well as we can.
3005   my $contact = FS::contact->by_selfservice_email($svc_acct->email);
3006   if ( $contact && $contact->custnum == $custnum ) {
3007     #svc_acct was successful but this one returns an error?  "shouldn't happen"
3008     #don't recheck is_password_allowed here; if the svc_acct password was
3009     #legal, that's good enough
3010     $error ||= $contact->change_password($p->{'new_password'});
3011   }
3012
3013   my($label, $value) = $svc_acct->cust_svc->label;
3014
3015   return { 'error' => $error,
3016            'label' => $label,
3017            'value' => $value,
3018          };
3019
3020 }
3021
3022 sub reset_passwd {
3023   my $p = shift;
3024
3025   my $info = skin_info($p);
3026
3027   my $conf = new FS::Conf;
3028   my $verification = $conf->config('selfservice-password_reset_verification')
3029     or return { %$info, 'error' => 'Password resets disabled' };
3030
3031   my $contact = '';
3032   my $svc_acct = '';
3033   my $cust_main = '';
3034   if ( $p->{'email'} ) { #new-style, changes contact and svc_acct
3035   
3036     $contact = FS::contact->by_selfservice_email($p->{'email'});
3037
3038     $cust_main = $contact->cust_main if $contact;
3039
3040     #also look for an svc_acct, otherwise it would be super confusing
3041
3042     my($username, $domain) = split('@', $p->{'email'});
3043     my $svc_domain = qsearchs('svc_domain', { 'domain' => $domain } );
3044     if ( $svc_domain ) {
3045       $svc_acct = qsearchs('svc_acct', { 'username' => $username,
3046                                          'domsvc'   => $svc_domain->svcnum  }
3047                           );
3048       if ( $svc_acct ) {
3049         my $cust_pkg = $svc_acct->cust_svc->cust_pkg;
3050         $cust_main ||= $cust_pkg->cust_main if $cust_pkg;
3051
3052         #precaution: don't change svc_acct password not part of the same
3053         # customer as contact
3054         $svc_acct = '' if ! $cust_pkg
3055                        || $cust_pkg->custnum != $cust_main->custnum;
3056       }
3057       
3058     }
3059
3060     return { %$info, 'error' => 'Email address not found' }
3061       unless $contact || $svc_acct;
3062
3063   } elsif ( $p->{'username'} ) { #old style, looks in svc_acct only
3064
3065     my $svc_domain = qsearchs('svc_domain', { 'domain' => $p->{'domain'} } )
3066       or return { %$info, 'error' => 'Account not found' };
3067
3068     $svc_acct = qsearchs('svc_acct', { 'username' => $p->{'username'},
3069                                        'domsvc'   => $svc_domain->svcnum  }
3070                         )
3071       or return { %$info, 'error' => 'Account not found' };
3072
3073     my $cust_pkg = $svc_acct->cust_svc->cust_pkg
3074       or return { %$info, 'error' => 'Account not found' };
3075
3076     $cust_main = $cust_pkg->cust_main;
3077
3078   }
3079
3080   my %verify = (
3081     'email'   => sub { 1; },
3082     'paymask' => sub { 
3083       my( $p, $cust_main ) = @_;
3084       $cust_main->payby =~ /^(CARD|DCRD|CHEK|DCHK)$/
3085         && $p->{'paymask'} eq substr($cust_main->paymask, -4)
3086     },
3087     'amount'  => sub {
3088       my( $p, $cust_main ) = @_;
3089       my $cust_pay = qsearchs({
3090         'table' => 'cust_pay',
3091         'hashref' => { 'custnum' => $cust_main->custnum },
3092         'order_by' => 'ORDER BY _date DESC LIMIT 1',
3093       })
3094         or return 0;
3095
3096       $p->{'amount'} == $cust_pay->paid;
3097     },
3098     'zip'     => sub {
3099       my( $p, $cust_main ) = @_;
3100       $p->{'zip'} eq $cust_main->zip
3101         || ( $cust_main->ship_zip && $p->{'zip'} eq $cust_main->ship_zip );
3102     },
3103   );
3104
3105   foreach my $verify ( split(',', $verification) ) {
3106
3107     &{ $verify{$verify} }( $p, $cust_main )
3108       or return { %$info, 'error' => 'Account not found' };
3109
3110   }
3111
3112   #okay, we're verified
3113
3114   if ( $contact ) {
3115
3116     my $error = $contact->send_reset_email(
3117                             'svcnum' => ($svc_acct ? $svc_acct->svcnum : ''),
3118                           );
3119
3120     if ( $error ) {
3121       return { %$info, 'error' => $error }; #????
3122     }
3123
3124   } elsif ( $svc_acct ) {
3125
3126     #create a unique session
3127
3128     my $reset_session = {
3129       'svcnum'   => $svc_acct->svcnum,
3130       'agentnum' => $svc_acct->cust_main->agentnum,
3131     };
3132
3133     my $timeout = '1 hour'; #?
3134
3135     my $reset_session_id;
3136     do {
3137       $reset_session_id = sha512_hex(time(). {}. rand(). $$)
3138     } until ( ! defined _cache->get("reset_passwd_$reset_session_id") );
3139       #just in case
3140
3141     _cache->set( "reset_passwd_$reset_session_id", $reset_session, $timeout );
3142
3143     #email it
3144
3145     my $msgnum = $conf->config('selfservice-password_reset_msgnum',
3146                                $cust_main->agentnum);
3147     #die "selfservice-password_reset_msgnum unset" unless $msgnum;
3148     return { %$info, 'error' => "selfservice-password_reset_msgnum unset" }
3149       unless $msgnum;
3150     my $msg_template = qsearchs('msg_template', { msgnum => $msgnum } );
3151     my $error = $msg_template->send( 'cust_main'     => $cust_main,
3152                                      'object'        => $svc_acct,
3153                                      'substitutions' => {
3154                                        'session_id' => $reset_session_id,
3155                                      }
3156                                    );
3157     if ( $error ) {
3158       return { %$info, 'error' => $error }; #????
3159     }
3160
3161   }
3162
3163   return { %$info, 'error' => '' };
3164 }
3165
3166 sub check_reset_passwd {
3167   my $p = shift;
3168
3169   my $conf = new FS::Conf;
3170   my $verification = $conf->config('selfservice-password_reset_verification')
3171     or return { 'error' => 'Password resets disabled' };
3172
3173   my $reset_session = _cache->get('reset_passwd_'. $p->{'session_id'})
3174     or return { 'error' => "Can't resume session" }; #better error message
3175
3176   if ( $reset_session->{'svcnum'} ) {
3177
3178     my $svcnum = $reset_session->{'svcnum'};
3179
3180     my $svc_acct = qsearchs('svc_acct', { 'svcnum' => $svcnum } )
3181       or return { 'error' => "Service not found" };
3182
3183     $p->{'agentnum'} = $svc_acct->cust_svc->cust_pkg->cust_main->agentnum;
3184     my $info = skin_info($p);
3185
3186     return { %$info,
3187              'error'      => '',
3188              'session_id' => $p->{'session_id'},
3189              'username'   => $svc_acct->username,
3190            };
3191
3192   } elsif ( $reset_session->{'contactnum'} ) {
3193
3194     my $contactnum = $reset_session->{'contactnum'};
3195
3196     my $contact = qsearchs('contact', { 'contactnum' => $contactnum } )
3197       or return { 'error' => "Contact not found" };
3198
3199     my @contact_email = $contact->contact_email;
3200     return { 'error' => 'No contact email' } unless @contact_email;
3201
3202     $p->{'agentnum'} = $contact->cust_main->agentnum;
3203     my $info = skin_info($p);
3204
3205     return { %$info,
3206              'error'      => '',
3207              'session_id' => $p->{'session_id'},
3208              'email'      => $contact_email[0]->email, #the first?
3209            };
3210
3211   } else {
3212
3213     return { 'error' => 'No svcnum or contactnum in session' }; #??
3214
3215   }
3216
3217 }
3218
3219 sub process_reset_passwd {
3220   my $p = shift;
3221
3222   my $conf = new FS::Conf;
3223   my $verification = $conf->config('selfservice-password_reset_verification')
3224     or return { 'error' => 'Password resets disabled' };
3225
3226   my $reset_session = _cache->get('reset_passwd_'. $p->{'session_id'})
3227     or return { 'error' => "Can't resume session" }; #better error message
3228
3229   my $info = '';
3230
3231   my $svc_acct = '';
3232   if ( $reset_session->{'svcnum'} ) {
3233
3234     my $svcnum = $reset_session->{'svcnum'};
3235
3236     $svc_acct = qsearchs('svc_acct', { 'svcnum' => $svcnum } )
3237       or return { 'error' => "Service not found" };
3238
3239     $p->{'agentnum'} ||= $svc_acct->cust_svc->cust_pkg->cust_main->agentnum;
3240     $info ||= skin_info($p);
3241
3242   }
3243
3244   my $contact = '';
3245   if ( $reset_session->{'contactnum'} ) {
3246
3247     my $contactnum = $reset_session->{'contactnum'};
3248
3249     $contact = qsearchs('contact', { 'contactnum' => $contactnum } )
3250       or return { 'error' => "Contact not found" };
3251
3252     $p->{'agentnum'} ||= $contact->cust_main->agentnum;
3253     $info ||= skin_info($p);
3254
3255   }
3256
3257   return { %$info, 'error' => "New passwords don't match." }
3258     if $p->{'new_password'} ne $p->{'new_password2'};
3259
3260   return { %$info, 'error' => 'Enter new password' }
3261     unless length($p->{'new_password'});
3262
3263   if ( $svc_acct ) {
3264
3265     my $error ||= $svc_acct->is_password_allowed($p->{'new_password'})
3266               ||  $svc_acct->set_password($p->{'new_password'})
3267               ||  $svc_acct->replace();
3268
3269     return { %$info, 'error' => $error } if $error;
3270
3271     #my($label, $value) = $svc_acct->cust_svc->label;
3272     #return { 'error' => $error,
3273     #         #'label' => $label,
3274     #         #'value' => $value,
3275     #       };
3276
3277   }
3278
3279   if ( $contact ) {
3280
3281     my $error = $contact->is_password_allowed($p->{'new_password'})
3282             ||  $contact->change_password($p->{'new_password'});
3283
3284     return { %$info, 'error' => $error }; # if $error;
3285
3286   }
3287
3288   #password changed ,so remove session, don't want it reused
3289   _cache->remove($p->{'session_id'});
3290
3291   return { %$info, 'error' => '' };
3292
3293 }
3294
3295 sub validate_passwd {
3296   my $p = shift;
3297
3298   my %result;
3299   %result = ( 'fieldid' => $p->{'fieldid'} )
3300     if $p->{'fieldid'} =~ /^\w+$/;
3301
3302   return { %result, 'password_invalid' => 'Enter new password' }
3303     unless length($p->{'check_password'});
3304
3305   my $svc_acct;
3306   if ($p->{'svcnum'}) {
3307     # false laziness with myaccount_passwd
3308     my($context, $session, $custnum) = _custoragent_session_custnum($p);
3309     return { %result, 'error' => $session } if $context eq 'error';
3310
3311     $custnum =~ /^(\d+)$/ or die "illegal custnum";
3312     my $search = " AND custnum = $1";
3313     $search .= " AND agentnum = ". $session->{'agentnum'} if $context eq 'agent';
3314
3315     $svc_acct = qsearchs( {
3316       'table'     => 'svc_acct',
3317       'addl_from' => 'LEFT JOIN cust_svc  USING ( svcnum  ) '.
3318                      'LEFT JOIN cust_pkg  USING ( pkgnum  ) '.
3319                      'LEFT JOIN cust_main USING ( custnum ) ',
3320       'hashref'   => { 'svcnum' => $p->{'svcnum'}, },
3321       'extra_sql' => $search, #important
3322     } )
3323       or return { %result, 'error' => "Service not found" };
3324     # end false laziness
3325   }
3326
3327   unless ($svc_acct) {
3328     my $conf = new FS::Conf;
3329     my $agentnum = $p->{'agentnum'};
3330     return { %result, 'password_valid' => 1 }
3331       if $conf->config_bool('password-insecure', $p->{'agentnum'});
3332   }
3333
3334   $svc_acct ||= new FS::svc_acct {};
3335
3336   my $error = $svc_acct->is_password_allowed($p->{'check_password'});
3337   return { %result, 'password_invalid' => $error } if $error;
3338   return { %result, 'password_valid' => 1 };
3339 }
3340
3341 sub list_tickets {
3342   my $p = shift;
3343   my($context, $session, $custnum) = _custoragent_session_custnum($p);
3344   return { 'error' => $session } if $context eq 'error';
3345
3346   my @tickets = ();
3347   if ( $session->{'pkgnum'} ) { 
3348
3349     #tickets for specific service with pkg-balances on
3350     my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
3351                                           'pkgnum'  => $session->{'pkgnum'} })
3352                      or return { 'error' => 'unknown package' };
3353     foreach my $cust_svc ( $cust_pkg->cust_svc ) {
3354       push @tickets, $cust_svc->tickets( $p->{status} );
3355     }
3356
3357   } else {
3358
3359     my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
3360       or return { 'error' => "unknown custnum $custnum" };
3361
3362     @tickets = $cust_main->tickets( $p->{status} );
3363   }
3364
3365   # unavoidable false laziness w/ httemplate/view/cust_main/tickets.html
3366   if ( $FS::TicketSystem::system && FS::TicketSystem->selfservice_priority ) {
3367     my $conf = new FS::Conf;
3368     my $dir = $conf->exists('ticket_system-priority_reverse') ? -1 : 1;
3369     +{ tickets => [ 
3370          sort { 
3371            (
3372              ($a->{'_selfservice_priority'} eq '') <=>
3373              ($b->{'_selfservice_priority'} eq '')
3374            ) ||
3375            ( $dir * 
3376              ($b->{'_selfservice_priority'} <=> $a->{'_selfservice_priority'})
3377            )
3378          } @tickets
3379        ]
3380     };
3381   } else {
3382     +{ tickets => \@tickets };
3383   }
3384
3385 }
3386
3387 sub create_ticket {
3388   my $p = shift;
3389   my($context, $session, $custnum) = _custoragent_session_custnum($p);
3390   return { 'error' => $session } if $context eq 'error';
3391
3392   warn "$me create_ticket: initializing ticket system\n" if $DEBUG;
3393   FS::TicketSystem->init();
3394
3395   my $conf = new FS::Conf;
3396   my $queue = $p->{'queue'}
3397               || $conf->config('ticket_system-selfservice_queueid')
3398               || $conf->config('ticket_system-default_queueid');
3399
3400   warn "$me create_ticket: creating ticket\n" if $DEBUG;
3401   my $err_or_ticket = FS::TicketSystem->create_ticket(
3402     '', #create RT session based on FS CurrentUser (fs_selfservice)
3403     'queue'   => $queue,
3404     'custnum' => $custnum,
3405     'svcnum'  => $session->{'svcnum'},
3406     map { $_ => $p->{$_} } qw( requestor cc subject message mime_type )
3407   );
3408
3409   if ( ref($err_or_ticket) ) {
3410     warn "$me create_ticket: successful: ". $err_or_ticket->id. "\n"
3411       if $DEBUG;
3412     return { 'error'     => '',
3413              'ticket_id' => $err_or_ticket->id,
3414            };
3415   } else {
3416     warn "$me create_ticket: unsuccessful: $err_or_ticket\n"
3417       if $DEBUG;
3418     return { 'error' => $err_or_ticket };
3419   }
3420
3421
3422 }
3423
3424 sub did_report {
3425   my $p = shift;
3426   my($context, $session, $custnum) = _custoragent_session_custnum($p);
3427   return { 'error' => $session } if $context eq 'error';
3428  
3429   return { error => 'requested format not implemented' } 
3430     unless ($p->{'format'} eq 'csv' || $p->{'format'} eq 'xls');
3431
3432   my $conf = new FS::Conf;
3433   my $age_threshold = 0;
3434   $age_threshold = time() - $conf->config('selfservice-recent-did-age')
3435     if ($p->{'recentonly'} && $conf->exists('selfservice-recent-did-age'));
3436
3437   my $search = { 'custnum' => $custnum };
3438   $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
3439   my $cust_main = qsearchs('cust_main', $search )
3440     or return { 'error' => "unknown custnum $custnum" };
3441
3442 # does it make more sense to just run one sql query for this instead of all the
3443 # insanity below? would increase performance greately for large data sets?
3444   my @svc_phone = ();
3445   foreach my $cust_pkg ( $cust_main->ncancelled_pkgs ) {
3446         my @part_svc = $cust_pkg->part_svc;
3447         foreach my $part_svc ( @part_svc ) {
3448             if($part_svc->svcdb eq 'svc_phone'){
3449                 my @cust_pkg_svc = @{$part_svc->cust_pkg_svc};
3450                 foreach my $cust_pkg_svc ( @cust_pkg_svc ) {
3451                     push @svc_phone, $cust_pkg_svc->svc_x
3452                         if $cust_pkg_svc->date_inserted >= $age_threshold;
3453                 }
3454             }
3455         }
3456   }
3457
3458   my $csv;
3459   my $xls;
3460   my($xls_r,$xls_c) = (0,0);
3461   my $xls_workbook;
3462   my $content = '';
3463   my @fields = qw( countrycode phonenum pin sip_password phone_name );
3464   if($p->{'format'} eq 'csv') {
3465     $csv = new Text::CSV_XS { 'always_quote' => 1,
3466                                  'eol'          => "\n",
3467                                 };
3468     return { 'error' => 'Unable to create CSV' } unless $csv->combine(@fields);
3469     $content .= $csv->string;
3470   }
3471   elsif($p->{'format'} eq 'xls') {
3472     my $XLS1 = new IO::Scalar \$content;
3473     $xls_workbook = Spreadsheet::WriteExcel->new($XLS1) 
3474         or return { 'error' => "Error opening .xls file: $!" };
3475     $xls = $xls_workbook->add_worksheet('DIDs');
3476     foreach ( @fields ) {
3477         $xls->write(0,$xls_c++,$_);
3478     }
3479     $xls_r++;
3480   }
3481
3482   foreach my $svc_phone ( @svc_phone ) {
3483     my @cols = map { $svc_phone->$_ } @fields;
3484     if($p->{'format'} eq 'csv') {
3485         return { 'error' => 'Unable to create CSV' } 
3486             unless $csv->combine(@cols);
3487         $content .= $csv->string;
3488     }
3489     elsif($p->{'format'} eq 'xls') {
3490         $xls_c = 0;
3491         foreach ( @cols ) {
3492             $xls->write($xls_r,$xls_c++,$_);
3493         }
3494         $xls_r++;
3495     }
3496   }
3497
3498   $xls_workbook->close() if $p->{'format'} eq 'xls';
3499   
3500   { content => $content, format => $p->{'format'}, };
3501 }
3502
3503 sub get_ticket {
3504   my $p = shift;
3505   my($context, $session, $custnum) = _custoragent_session_custnum($p);
3506   return { 'error' => $session } if $context eq 'error';
3507
3508 #  warn "$me get_ticket: initializing ticket system\n" if $DEBUG;
3509 #  FS::TicketSystem->init();
3510 #  return { 'error' => 'get_ticket configuration error' }
3511 #    if $FS::TicketSystem::system ne 'RT_Internal';
3512
3513   # check existence and ownership as part of this
3514   warn "$me get_ticket: fetching ticket\n" if $DEBUG;
3515   my $rt_session = FS::TicketSystem->session('');
3516   my $Ticket = FS::TicketSystem->get_ticket_object(
3517     $rt_session, 
3518     ticket_id => $p->{'ticket_id'},
3519     custnum => $custnum
3520   );
3521   return { 'error' => 'ticket not found' } if !$Ticket;
3522
3523   if ( length( $p->{'subject'} || '' ) ) {
3524     # subject change
3525     if ( $p->{'subject'} ne $Ticket->Subject ) {
3526       my ($val, $msg) = $Ticket->SetSubject($p->{'subject'});
3527       return { 'error' => "unable to set subject: $msg" } if !$val;
3528     }
3529   }
3530
3531   if(length($p->{'reply'})) {
3532     my @err_or_res = FS::TicketSystem->correspond_ticket(
3533       $rt_session,
3534       'ticket_id' => $p->{'ticket_id'},
3535       'content' => $p->{'reply'},
3536     );
3537
3538     return { 'error' => 'unable to reply to ticket' } 
3539     unless ( $err_or_res[0] != 0 && defined $err_or_res[2] );
3540   }
3541
3542   warn "$me get_ticket: getting ticket history\n" if $DEBUG;
3543   my $err_or_ticket = FS::TicketSystem->get_ticket(
3544     $rt_session,
3545     'ticket_id' => $p->{'ticket_id'},
3546   );
3547
3548   if ( !ref($err_or_ticket) ) { # there is no way this should ever happen
3549     warn "$me get_ticket: unsuccessful: $err_or_ticket\n"
3550       if $DEBUG;
3551     return { 'error' => $err_or_ticket };
3552   }
3553
3554   my @custs = @{$err_or_ticket->{'custs'}};
3555   my @txns = @{$err_or_ticket->{'txns'}};
3556   my @filtered_txns;
3557
3558   # superseded by check in get_ticket_object
3559   #return { 'error' => 'invalid ticket requested' } 
3560   #unless grep($_ eq $custnum, @custs);
3561
3562   foreach my $txn ( @txns ) {
3563     push @filtered_txns, $txn 
3564     if ($txn->{'type'} eq 'EmailRecord' 
3565       || $txn->{'type'} eq 'Correspond'
3566       || $txn->{'type'} eq 'Create');
3567   }
3568
3569   warn "$me get_ticket: successful: \n"
3570   if $DEBUG;
3571   return { 'error'     => '',
3572     'transactions' => \@filtered_txns,
3573     'ticket_fields' => $err_or_ticket->{'fields'},
3574     'ticket_id' => $p->{'ticket_id'},
3575   };
3576 }
3577
3578 sub adjust_ticket_priority {
3579   my $p = shift;
3580   my($context, $session, $custnum) = _custoragent_session_custnum($p);
3581   return { 'error' => $session } if $context eq 'error';
3582
3583 #  warn "$me adjust_ticket_priority: initializing ticket system\n" if $DEBUG;
3584 #  FS::TicketSystem->init;
3585   my $ss_priority = FS::TicketSystem->selfservice_priority;
3586
3587   return { 'error' => 'adjust_ticket_priority configuration error' }
3588     if $FS::TicketSystem::system ne 'RT_Internal'
3589       or !$ss_priority;
3590
3591   my $values = $p->{'values'}; #hashref, id => priority value
3592   my %ticket_error;
3593
3594   foreach my $id (keys %$values) {
3595     warn "$me adjust_ticket_priority: fetching ticket $id\n" if $DEBUG;
3596     my $Ticket = FS::TicketSystem->get_ticket_object('',
3597       'ticket_id' => $id,
3598       'custnum'   => $custnum,
3599     );
3600     if ( !$Ticket ) {
3601       $ticket_error{$id} = 'ticket not found';
3602       next;
3603     }
3604     
3605   # RT API stuff--would we gain anything by wrapping this in FS::TicketSystem?
3606   # We're not going to implement it for RT_External.
3607     my $old_value = $Ticket->FirstCustomFieldValue($ss_priority);
3608     my $new_value = $values->{$id};
3609     next if $old_value eq $new_value;
3610
3611     warn "$me adjust_ticket_priority: updating ticket $id\n" if $DEBUG;
3612
3613     # AddCustomFieldValue works fine (replacing any existing value) if it's 
3614     # a single-valued custom field, which it should be.  If it's not, you're 
3615     # doing something wrong.
3616     my ($val, $msg);
3617     if ( length($new_value) ) {
3618       ($val, $msg) = $Ticket->AddCustomFieldValue( 
3619         Field => $ss_priority,
3620         Value => $new_value,
3621       );
3622     }
3623     else {
3624       ($val, $msg) = $Ticket->DeleteCustomFieldValue(
3625         Field => $ss_priority,
3626         Value => $old_value,
3627       );
3628     }
3629
3630     $ticket_error{$id} = $msg if !$val;
3631     warn "$me adjust_ticket_priority: $id: $msg\n" if $DEBUG and !$val;
3632   }
3633   return { 'error' => '',
3634            'ticket_error' => \%ticket_error,
3635            %{ customer_info($p) } # send updated customer info back
3636          }
3637 }
3638
3639 #--
3640
3641 sub _custoragent_session_custnum {
3642   my $p = shift;
3643
3644   my($context, $session, $custnum);
3645   if ( $p->{'session_id'} ) {
3646
3647     $context = 'customer';
3648     $session = _cache->get($p->{'session_id'})
3649       or return ( 'error' => "Can't resume session" ); #better error message
3650     $custnum = $session->{'custnum'};
3651
3652   } elsif ( $p->{'agent_session_id'} ) {
3653
3654     $context = 'agent';
3655     my $agent_cache = new FS::ClientAPI_SessionCache( {
3656       'namespace' => 'FS::ClientAPI::Agent',
3657     } );
3658     $session = $agent_cache->get($p->{'agent_session_id'})
3659       or return ( 'error' => "Can't resume session" ); #better error message
3660     $custnum = $p->{'custnum'};
3661
3662   } else {
3663     $context = 'error';
3664     return ( 'error' => "Can't resume session" ); #better error message
3665   }
3666
3667   ($context, $session, $custnum);
3668
3669 }
3670
3671 1;
3672