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