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