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