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