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