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