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