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