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