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_credit'=>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 $bill_error =    $cust_main->bill
2504                      || $cust_main->apply_payments_and_credits;
2505
2506     $bill_error ||= $cust_main->realtime_collect('selfservice' => 1)
2507       if $cust_main->payby =~ /^(CARD|CHEK)$/;
2508
2509     if (    $cust_main->balance > $old_balance
2510          && $cust_main->balance > 0
2511          && ( $cust_main->payby !~ /^(BILL|DCRD|DCHK)$/
2512                 || $status eq 'suspended'
2513             )
2514        )
2515     {
2516       unless ( $opt{'no_credit'} ) {
2517         #this makes sense.  credit is "un-doing" the invoice
2518         my $conf = new FS::Conf;
2519         $cust_main->credit( sprintf("%.2f", $cust_main->balance-$old_balance ),
2520                             'self-service decline',
2521                             reason_type=>$conf->config('signup_credit_type'),
2522                           );
2523         $cust_main->apply_credits( 'order' => 'newest' );
2524       }
2525
2526       return { 'error' => '_decline', 'bill_error' => $bill_error };
2527     }
2528
2529     '';
2530 }
2531
2532 sub renew_info {
2533   my $p = shift;
2534
2535   my($context, $session, $custnum) = _custoragent_session_custnum($p);
2536   return { 'error' => $session } if $context eq 'error';
2537
2538   my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
2539     or return { 'error' => "unknown custnum $custnum" };
2540
2541   my @cust_pkg = sort { $a->bill <=> $b->bill }
2542                  grep { $_->part_pkg->freq ne '0' }
2543                  $cust_main->ncancelled_pkgs;
2544
2545   #return { 'error' => 'No active packages to renew.' } unless @cust_pkg;
2546
2547   my $total = $cust_main->balance;
2548
2549   my @array = map {
2550                     my $bill = $_->bill;
2551                     $total += $_->part_pkg->base_recur($_, \$bill);
2552                     my $renew_date = $_->part_pkg->add_freq($_->bill);
2553                     {
2554                       'pkgnum'             => $_->pkgnum,
2555                       'amount'             => sprintf('%.2f', $total),
2556                       'bill_date'          => $_->bill,
2557                       'bill_date_pretty'   => time2str('%x', $_->bill),
2558                       'renew_date'         => $renew_date,
2559                       'renew_date_pretty'  => time2str('%x', $renew_date),
2560                       'expire_date'        => $_->expire,
2561                       'expire_date_pretty' => time2str('%x', $_->expire),
2562                     };
2563                   }
2564                   @cust_pkg;
2565
2566   return { 'dates' => \@array };
2567
2568 }
2569
2570 sub payment_info_renew_info {
2571   my $p = shift;
2572   my $renew_info   = renew_info($p);
2573   my $payment_info = payment_info($p);
2574   return { %$renew_info,
2575            %$payment_info,
2576          };
2577 }
2578
2579 sub order_renew {
2580   my $p = shift;
2581
2582   my($context, $session, $custnum) = _custoragent_session_custnum($p);
2583   return { 'error' => $session } if $context eq 'error';
2584
2585   my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
2586     or return { 'error' => "unknown custnum $custnum" };
2587
2588   my $date = $p->{'date'};
2589
2590   my $now = time;
2591
2592   #freeside-daily -n -d $date fs_daily $custnum
2593   $cust_main->bill_and_collect( 'time'         => $date,
2594                                 'invoice_time' => $now,
2595                                 'actual_time'  => $now,
2596                                 'check_freq'   => '1d',
2597                               );
2598
2599   return { 'error' => '' };
2600
2601 }
2602
2603 sub suspend_pkg {
2604   my $p = shift;
2605   my $session = _cache->get($p->{'session_id'})
2606     or return { 'error' => "Can't resume session" }; #better error message
2607
2608   my $custnum = $session->{'custnum'};
2609
2610   my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
2611     or return { 'error' => "unknown custnum $custnum" };
2612
2613   my $conf = new FS::Conf;
2614   my $reasonnum = 
2615     $conf->config('selfservice-self_suspend_reason', $cust_main->agentnum)
2616       or return { 'error' => 'Permission denied' };
2617
2618   my $pkgnum = $p->{'pkgnum'};
2619
2620   my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
2621                                         'pkgnum'  => $pkgnum,   } )
2622     or return { 'error' => "unknown pkgnum $pkgnum" };
2623
2624   my $error = $cust_pkg->suspend(reason => $reasonnum);
2625   return { 'error' => $error };
2626
2627 }
2628
2629 sub cancel_pkg {
2630   my $p = shift;
2631   my $session = _cache->get($p->{'session_id'})
2632     or return { 'error' => "Can't resume session" }; #better error message
2633
2634   my $custnum = $session->{'custnum'};
2635
2636   my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
2637     or return { 'error' => "unknown custnum $custnum" };
2638
2639   my $pkgnum = $p->{'pkgnum'};
2640
2641   my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
2642                                         'pkgnum'  => $pkgnum,   } )
2643     or return { 'error' => "unknown pkgnum $pkgnum" };
2644
2645   my $error = $cust_pkg->cancel('quiet' => 1);
2646   return { 'error' => $error };
2647
2648 }
2649
2650 sub provision_phone {
2651   my $p = shift;
2652   my @bulkdid;
2653   @bulkdid = @{$p->{'bulkdid'}} if $p->{'bulkdid'};
2654
2655   #editing an existing phone number
2656   if ( $p->{'svcnum'} && $p->{'svcnum'} =~ /^\d+$/ ) {
2657       my($context, $session, $custnum) = _custoragent_session_custnum($p);
2658       return { 'error' => $session } if $context eq 'error';
2659     
2660       my $svc_phone = qsearchs('svc_phone', { svcnum => $p->{'svcnum'} });
2661       return { 'error' => 'service not found' } unless $svc_phone;
2662       return { 'error' => 'invalid svcnum' } 
2663         if $svc_phone && $svc_phone->cust_svc->cust_pkg->custnum != $custnum;
2664
2665       $svc_phone->email($p->{'email'}) 
2666         if $svc_phone->email ne $p->{'email'} && $p->{'email'} =~ /^([\w\.\d@]+|)$/;
2667       $svc_phone->forwarddst($p->{'forwarddst'}) 
2668         if $svc_phone->forwarddst ne $p->{'forwarddst'} 
2669             && $p->{'forwarddst'} =~ /^(\d+|)$/;
2670       return { 'error' => $svc_phone->replace };
2671  }
2672
2673   # single DID LNP
2674   unless ( $p->{'lnp'} ) {
2675     $p->{'lnp_desired_due_date'} = parse_datetime($p->{'lnp_desired_due_date'});
2676     $p->{'lnp_status'} = "portingin";
2677     return _provision( 'FS::svc_phone',
2678                   [qw(lnp_desired_due_date lnp_other_provider 
2679                     lnp_other_provider_account phonenum countrycode lnp_status)],
2680                   [qw(phonenum countrycode)],
2681                   $p,
2682                   @_
2683                 );
2684   }
2685
2686   # single DID order (the usual case)
2687   unless (scalar(@bulkdid)) {
2688     return _provision( 'FS::svc_phone',
2689                   [qw(phonenum countrycode)],
2690                   [qw(phonenum countrycode)],
2691                   $p,
2692                   @_
2693                 );
2694   }
2695
2696   # bulk DID order case
2697   my $error;
2698   foreach my $did ( @bulkdid ) {
2699     $did =~ s/[^0-9]//g;
2700     $error = _provision( 'FS::svc_phone',
2701               [qw(phonenum countrycode)],
2702               [qw(phonenum countrycode)],
2703               {
2704                 'pkgnum' => $p->{'pkgnum'},
2705                 'svcpart' => $p->{'svcpart'},
2706                 'phonenum' => $did,
2707                 'countrycode' => $p->{'countrycode'},
2708                 'session_id' => $p->{'session_id'},
2709               }
2710             );
2711     return $error if ($error->{'error'} && length($error->{'error'}) > 1);
2712   }
2713   { 'bulkdid' => [ @bulkdid ], 'svc' => $error->{'svc'} }
2714 }
2715
2716 sub provision_pbx {
2717   my $p = shift;
2718   warn "provision_pbx called\n"
2719     if $DEBUG;
2720
2721   warn "provision_pbx calling _provision\n"
2722     if $DEBUG;
2723   _provision( 'FS::svc_pbx',
2724               [qw(id title max_extensions max_simultaneous ip_addr)],
2725               [qw(id title max_extensions max_simultaneous ip_addr)],
2726               $p,
2727               @_
2728             );
2729 }
2730
2731 sub provision_acct {
2732   my $p = shift;
2733   warn "provision_acct called\n"
2734     if $DEBUG;
2735
2736   return { 'error' => gettext('passwords_dont_match') }
2737     if $p->{'_password'} ne $p->{'_password2'};
2738   return { 'error' => gettext('empty_password') }
2739     unless length($p->{'_password'});
2740  
2741   if ($p->{'domsvc'}) {
2742     my %domains = domain_select_hash FS::svc_acct(map { $_ => $p->{$_} }
2743                                                   qw ( svcpart pkgnum ) );
2744     return { 'error' => gettext('invalid_domain') }
2745       unless ($domains{$p->{'domsvc'}});
2746   }
2747
2748   warn "provision_acct calling _provision\n"
2749     if $DEBUG;
2750   _provision( 'FS::svc_acct',
2751               [qw(username _password domsvc)],
2752               [qw(username _password domsvc)],
2753               $p,
2754               @_
2755             );
2756 }
2757
2758 sub provision_external {
2759   my $p = shift;
2760   #_provision( 'FS::svc_external', [qw(id title)], [qw(id title)], $p, @_ );
2761   _provision( 'FS::svc_external',
2762               [],
2763               [qw(id title)],
2764               $p,
2765               @_
2766             );
2767 }
2768
2769 sub provision_forward {
2770   my $p = shift;
2771   _provision( 'FS::svc_forward',
2772               ['srcsvc','src','dstsvc','dst'],
2773               [],
2774               $p,
2775             );
2776 }
2777
2778 sub _provision {
2779   my( $class, $fields, $return_fields, $p ) = splice(@_, 0, 4);
2780   warn "_provision called for $class\n"
2781     if $DEBUG;
2782
2783   my($context, $session, $custnum) = _custoragent_session_custnum($p);
2784   return { 'error' => $session } if $context eq 'error';
2785
2786   my $search = { 'custnum' => $custnum };
2787   $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2788   my $cust_main = qsearchs('cust_main', $search )
2789     or return { 'error' => "unknown custnum $custnum" };
2790
2791   my $pkgnum = $p->{'pkgnum'};
2792
2793   warn "searching for custnum $custnum pkgnum $pkgnum\n"
2794     if $DEBUG;
2795   my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
2796                                         'pkgnum'  => $pkgnum,
2797                                                                } )
2798     or return { 'error' => "unknown pkgnum $pkgnum" };
2799
2800   warn "searching for svcpart ". $p->{'svcpart'}. "\n"
2801     if $DEBUG;
2802   my $part_svc = qsearchs('part_svc', { 'svcpart' => $p->{'svcpart'} } )
2803     or return { 'error' => "unknown svcpart $p->{'svcpart'}" };
2804
2805   return { error=> 'svcpart '. $p->{'svcpart'}. " is not a $class definition" }
2806     if $class ne 'FS::'. $part_svc->svcdb;
2807
2808   warn "creating $class record\n"
2809     if $DEBUG;
2810   my $svc_x = $class->new( {
2811     'pkgnum'  => $p->{'pkgnum'},
2812     'svcpart' => $p->{'svcpart'},
2813     map { $_ => $p->{$_} } @$fields
2814   } );
2815
2816   my %insert_args = ();
2817   #i shouldn't be a special case here (pass an option or something)
2818   if ( $class eq 'FS::svc_phone'
2819          && grep length($p->{$_}), @location_editable_fields
2820      )
2821   {
2822     $insert_args{'cust_location'} = new FS::cust_location {
2823       map { $_ => $p->{$_} } @location_editable_fields
2824     };
2825   }
2826
2827   warn "inserting $class record\n"
2828     if $DEBUG;
2829   my $error = $svc_x->insert(%insert_args);
2830
2831   unless ( $error ) {
2832     warn "finding inserted record for svcnum ". $svc_x->svcnum. "\n"
2833       if $DEBUG;
2834     $svc_x = qsearchs($svc_x->table, { 'svcnum' => $svc_x->svcnum })
2835   }
2836
2837   my $return = { 'svc'   => $part_svc->svc,
2838                  'error' => $error,
2839                  map { $_ => $svc_x->get($_) } @$return_fields
2840                };
2841   warn "_provision returning ". Dumper($return). "\n"
2842     if $DEBUG;
2843   return $return;
2844
2845 }
2846
2847 sub part_svc_info {
2848   my $p = shift;
2849
2850   my($context, $session, $custnum) = _custoragent_session_custnum($p);
2851   return { 'error' => $session } if $context eq 'error';
2852
2853   my $search = { 'custnum' => $custnum };
2854   $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2855   my $cust_main = qsearchs('cust_main', $search )
2856     or return { 'error' => "unknown custnum $custnum" };
2857
2858   my $pkgnum = $p->{'pkgnum'};
2859
2860   my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
2861                                         'pkgnum'  => $pkgnum,
2862                                                                } )
2863     or return { 'error' => "unknown pkgnum $pkgnum" };
2864
2865   my $svcpart = $p->{'svcpart'};
2866
2867   my $pkg_svc = qsearchs('pkg_svc', { 'pkgpart' => $cust_pkg->pkgpart,
2868                                       'svcpart' => $svcpart,           } )
2869     or return { 'error' => "unknown svcpart $svcpart for pkgnum $pkgnum" };
2870   my $part_svc = $pkg_svc->part_svc;
2871
2872   my $conf = new FS::Conf;
2873
2874   my $ret = {
2875     'svc'     => $part_svc->svc,
2876     'svcdb'   => $part_svc->svcdb,
2877     'pkgnum'  => $pkgnum,
2878     'svcpart' => $svcpart,
2879     'custnum' => $custnum,
2880
2881     'security_phrase' => 0, #XXX !
2882     'svc_acct_pop'    => [], #XXX !
2883     'popnum'          => '',
2884     'init_popstate'   => '',
2885     'popac'           => '',
2886     'acstate'         => '',
2887
2888     'small_custview' =>
2889       small_custview( $cust_main, $conf->config('countrydefault') ),
2890
2891   };
2892
2893   if ($p->{'svcnum'} && $p->{'svcnum'} =~ /^\d+$/ 
2894                      && $ret->{'svcdb'} eq 'svc_phone') {
2895         $ret->{'svcnum'} = $p->{'svcnum'};
2896         my $svc_phone = qsearchs('svc_phone', { svcnum => $p->{'svcnum'} });
2897         if ( $svc_phone && $svc_phone->cust_svc->cust_pkg->custnum == $custnum ) {
2898             $ret->{'email'} = $svc_phone->email;
2899             $ret->{'forwarddst'} = $svc_phone->forwarddst;
2900         }
2901   }
2902
2903   if ($ret->{'svcdb'} eq 'svc_forward') {
2904     $ret->{'forward_emails'} = {$cust_pkg->forward_emails()};
2905   }
2906
2907   $ret;
2908 }
2909
2910 sub unprovision_svc {
2911   my $p = shift;
2912
2913   my($context, $session, $custnum) = _custoragent_session_custnum($p);
2914   return { 'error' => $session } if $context eq 'error';
2915
2916   my $search = { 'custnum' => $custnum };
2917   $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2918   my $cust_main = qsearchs('cust_main', $search )
2919     or return { 'error' => "unknown custnum $custnum" };
2920
2921   my $svcnum = $p->{'svcnum'};
2922
2923   my $cust_svc = qsearchs('cust_svc', { 'svcnum'  => $svcnum, } )
2924     or return { 'error' => "unknown svcnum $svcnum" };
2925
2926   return { 'error' => "Service $svcnum does not belong to customer $custnum" }
2927     unless $cust_svc->cust_pkg->custnum == $custnum;
2928
2929   my $conf = new FS::Conf;
2930
2931   return { 'svc'   => $cust_svc->part_svc->svc,
2932            'error' => $cust_svc->cancel,
2933            'small_custview' =>
2934              small_custview( $cust_main, $conf->config('countrydefault') ),
2935          };
2936
2937 }
2938
2939 sub myaccount_passwd {
2940   my $p = shift;
2941   my($context, $session, $custnum) = _custoragent_session_custnum($p);
2942   return { 'error' => $session } if $context eq 'error';
2943
2944   return { 'error' => "New passwords don't match." }
2945     if $p->{'new_password'} ne $p->{'new_password2'};
2946
2947   return { 'error' => 'Enter new password' }
2948     unless length($p->{'new_password'});
2949
2950   #my $search = { 'custnum' => $custnum };
2951   #$search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2952   $custnum =~ /^(\d+)$/ or die "illegal custnum";
2953   my $search = " AND custnum = $1";
2954   $search .= " AND agentnum = ". $session->{'agentnum'} if $context eq 'agent';
2955
2956   my $svc_acct = qsearchs( {
2957     'table'     => 'svc_acct',
2958     'addl_from' => 'LEFT JOIN cust_svc  USING ( svcnum  ) '.
2959                    'LEFT JOIN cust_pkg  USING ( pkgnum  ) '.
2960                    'LEFT JOIN cust_main USING ( custnum ) ',
2961     'hashref'   => { 'svcnum' => $p->{'svcnum'}, },
2962     'extra_sql' => $search, #important
2963   } )
2964     or return { 'error' => "Service not found" };
2965
2966   my $error = '';
2967
2968   my $conf = new FS::Conf;
2969
2970   return { 'error' => 'Incorrect current password.' }
2971     if  ( exists($p->{'old_password'})
2972           || $conf->exists('selfservice-password_change_oldpass')
2973         )
2974     && ! $svc_acct->check_password($p->{'old_password'});
2975
2976   $error = 'Password too short.'
2977     if length($p->{'new_password'}) < ($conf->config('passwordmin') || 6);
2978   $error = 'Password too long.'
2979     if length($p->{'new_password'}) > ($conf->config('passwordmax') || 8);
2980
2981   $svc_acct->set_password($p->{'new_password'});
2982   $error ||= $svc_acct->replace();
2983
2984   #regular pw change in self-service should change contact pw too, otherwise its
2985   #way too confusing.  hell its confusing they're separate at all, but alas.
2986   #need to support the "ISP provides email that's used as a contact email" case
2987   #as well as we can.
2988   my $contact = FS::contact->by_selfservice_email($svc_acct->email);
2989   if ( $contact && qsearchs('cust_contact', { contactnum=> $contact->contactnum,
2990                                               custnum   => $custnum,
2991                                               selfservice_access => 'Y',
2992                                             }
2993                            )
2994   ) {
2995     #svc_acct was successful but this one returns an error?  "shouldn't happen"
2996     $error ||= $contact->change_password($p->{'new_password'});
2997   }
2998
2999   my($label, $value) = $svc_acct->cust_svc->label;
3000
3001   return { 'error' => $error,
3002            'label' => $label,
3003            'value' => $value,
3004          };
3005
3006 }
3007
3008 sub reset_passwd {
3009   my $p = shift;
3010
3011   my $info = skin_info($p);
3012
3013   my $conf = new FS::Conf;
3014   my $verification = $conf->config('selfservice-password_reset_verification')
3015     or return { %$info, 'error' => 'Password resets disabled' };
3016
3017   my $contact = '';
3018   my $svc_acct = '';
3019   my $cust_main = '';
3020   if ( $p->{'email'} ) { #new-style, changes contact and svc_acct
3021   
3022     $contact = FS::contact->by_selfservice_email($p->{'email'});
3023
3024     if ( $contact ) {
3025       my @cust_contact = grep $_->selfservice_access, $contact->cust_contact;
3026       $cust_main = $cust_contact[0]->cust_main if scalar(@cust_contact) == 1;
3027     }
3028
3029     #also look for an svc_acct, otherwise it would be super confusing
3030
3031     my($username, $domain) = split('@', $p->{'email'});
3032     my $svc_domain = qsearchs('svc_domain', { 'domain' => $domain } );
3033     if ( $svc_domain ) {
3034       $svc_acct = qsearchs('svc_acct', { 'username' => $username,
3035                                          'domsvc'   => $svc_domain->svcnum  }
3036                           );
3037       if ( $svc_acct ) {
3038         my $cust_pkg = $svc_acct->cust_svc->cust_pkg;
3039         $cust_main ||= $cust_pkg->cust_main if $cust_pkg;
3040
3041         #precaution: don't change svc_acct password not part of the same
3042         # customer as contact
3043         $svc_acct = '' if ! $cust_pkg
3044                        || $cust_pkg->custnum != $cust_main->custnum;
3045       }
3046       
3047     }
3048
3049     return { %$info, 'error' => 'Email address not found' }
3050       unless $contact || $svc_acct;
3051
3052   } elsif ( $p->{'username'} ) { #old style, looks in svc_acct only
3053
3054     my $svc_domain = qsearchs('svc_domain', { 'domain' => $p->{'domain'} } )
3055       or return { %$info, 'error' => 'Account not found' };
3056
3057     $svc_acct = qsearchs('svc_acct', { 'username' => $p->{'username'},
3058                                        'domsvc'   => $svc_domain->svcnum  }
3059                         )
3060       or return { %$info, 'error' => 'Account not found' };
3061
3062     my $cust_pkg = $svc_acct->cust_svc->cust_pkg
3063       or return { %$info, 'error' => 'Account not found' };
3064
3065     $cust_main = $cust_pkg->cust_main;
3066
3067   }
3068
3069   return { %$info, 'error' => 'Multi-customer contacts incompatible with customer-based verification' }
3070     if ! $cust_main && $verification ne 'email';
3071
3072   my %verify = (
3073     'email'   => sub { 1; },
3074     'paymask' => sub { 
3075       my( $p, $cust_main ) = @_;
3076       $cust_main->payby =~ /^(CARD|DCRD|CHEK|DCHK)$/
3077         && $p->{'paymask'} eq substr($cust_main->paymask, -4)
3078     },
3079     'amount'  => sub {
3080       my( $p, $cust_main ) = @_;
3081       my $cust_pay = qsearchs({
3082         'table' => 'cust_pay',
3083         'hashref' => { 'custnum' => $cust_main->custnum },
3084         'order_by' => 'ORDER BY _date DESC LIMIT 1',
3085       })
3086         or return 0;
3087
3088       $p->{'amount'} == $cust_pay->paid;
3089     },
3090     'zip'     => sub {
3091       my( $p, $cust_main ) = @_;
3092       $p->{'zip'} eq $cust_main->zip
3093         || ( $cust_main->ship_zip && $p->{'zip'} eq $cust_main->ship_zip );
3094     },
3095   );
3096
3097   foreach my $verify ( split(',', $verification) ) {
3098
3099     &{ $verify{$verify} }( $p, $cust_main )
3100       or return { %$info, 'error' => 'Account not found' };
3101
3102   }
3103
3104   #okay, we're verified
3105
3106   if ( $contact ) {
3107
3108     my $error = $contact->send_reset_email(
3109                             'svcnum' => ($svc_acct ? $svc_acct->svcnum : ''),
3110                           );
3111
3112     if ( $error ) {
3113       return { %$info, 'error' => $error }; #????
3114     }
3115
3116   } elsif ( $svc_acct ) {
3117
3118     #create a unique session
3119
3120     my $reset_session = {
3121       'svcnum'   => $svc_acct->svcnum,
3122       'agentnum' => $svc_acct->cust_main->agentnum,
3123     };
3124
3125     my $timeout = '1 hour'; #?
3126
3127     my $reset_session_id;
3128     do {
3129       $reset_session_id = sha512_hex(time(). {}. rand(). $$)
3130     } until ( ! defined _cache->get("reset_passwd_$reset_session_id") );
3131       #just in case
3132
3133     _cache->set( "reset_passwd_$reset_session_id", $reset_session, $timeout );
3134
3135     #email it
3136
3137     my $msgnum = $conf->config('selfservice-password_reset_msgnum',
3138                                $cust_main->agentnum);
3139     #die "selfservice-password_reset_msgnum unset" unless $msgnum;
3140     return { %$info, 'error' => "selfservice-password_reset_msgnum unset" }
3141       unless $msgnum;
3142     my $msg_template = qsearchs('msg_template', { msgnum => $msgnum } );
3143     my $error = $msg_template->send( 'cust_main'     => $cust_main,
3144                                      'object'        => $svc_acct,
3145                                      'substitutions' => {
3146                                        'session_id' => $reset_session_id,
3147                                      }
3148                                    );
3149     if ( $error ) {
3150       return { %$info, 'error' => $error }; #????
3151     }
3152
3153   }
3154
3155   return { %$info, 'error' => '' };
3156 }
3157
3158 sub check_reset_passwd {
3159   my $p = shift;
3160
3161   my $conf = new FS::Conf;
3162   my $verification = $conf->config('selfservice-password_reset_verification')
3163     or return { 'error' => 'Password resets disabled' };
3164
3165   my $reset_session = _cache->get('reset_passwd_'. $p->{'session_id'})
3166     or return { 'error' => "Can't resume session" }; #better error message
3167
3168   if ( $reset_session->{'svcnum'} ) {
3169
3170     my $svcnum = $reset_session->{'svcnum'};
3171
3172     my $svc_acct = qsearchs('svc_acct', { 'svcnum' => $svcnum } )
3173       or return { 'error' => "Service not found" };
3174
3175     $p->{'agentnum'} = $svc_acct->cust_svc->cust_pkg->cust_main->agentnum;
3176     my $info = skin_info($p);
3177
3178     return { %$info,
3179              'error'      => '',
3180              'session_id' => $p->{'session_id'},
3181              'username'   => $svc_acct->username,
3182            };
3183
3184   } elsif ( $reset_session->{'contactnum'} ) {
3185
3186     my $contactnum = $reset_session->{'contactnum'};
3187
3188     my $contact = qsearchs('contact', { 'contactnum' => $contactnum } )
3189       or return { 'error' => "Contact not found" };
3190
3191     my @contact_email = $contact->contact_email;
3192     return { 'error' => 'No contact email' } unless @contact_email;
3193
3194     my @cust_contact = grep $_->selfservice_access, $contact->cust_contact;
3195     $p->{'agentnum'} = $cust_contact[0]->cust_main->agentnum
3196       if scalar(@cust_contact) == 1;
3197     my $info = skin_info($p);
3198
3199     return { %$info,
3200              'error'      => '',
3201              'session_id' => $p->{'session_id'},
3202              'email'      => $contact_email[0]->email, #the first?
3203            };
3204
3205   } else {
3206
3207     return { 'error' => 'No svcnum or contactnum in session' }; #??
3208
3209   }
3210
3211 }
3212
3213 sub process_reset_passwd {
3214   my $p = shift;
3215
3216   my $conf = new FS::Conf;
3217   my $verification = $conf->config('selfservice-password_reset_verification')
3218     or return { 'error' => 'Password resets disabled' };
3219
3220   my $reset_session = _cache->get('reset_passwd_'. $p->{'session_id'})
3221     or return { 'error' => "Can't resume session" }; #better error message
3222
3223   my $info = '';
3224
3225   my $svc_acct = '';
3226   if ( $reset_session->{'svcnum'} ) {
3227
3228     my $svcnum = $reset_session->{'svcnum'};
3229
3230     $svc_acct = qsearchs('svc_acct', { 'svcnum' => $svcnum } )
3231       or return { 'error' => "Service not found" };
3232
3233     $p->{'agentnum'} ||= $svc_acct->cust_svc->cust_pkg->cust_main->agentnum;
3234     $info ||= skin_info($p);
3235
3236   }
3237
3238   my $contact = '';
3239   if ( $reset_session->{'contactnum'} ) {
3240
3241     my $contactnum = $reset_session->{'contactnum'};
3242
3243     $contact = qsearchs('contact', { 'contactnum' => $contactnum } )
3244       or return { 'error' => "Contact not found" };
3245
3246     my @cust_contact = grep $_->selfservice_access, $contact->cust_contact;
3247     $p->{'agentnum'} = $cust_contact[0]->cust_main->agentnum
3248       if scalar(@cust_contact) == 1;
3249     $info ||= skin_info($p);
3250
3251   }
3252
3253   return { %$info, 'error' => "New passwords don't match." }
3254     if $p->{'new_password'} ne $p->{'new_password2'};
3255
3256   return { %$info, 'error' => 'Enter new password' }
3257     unless length($p->{'new_password'});
3258
3259   if ( $svc_acct ) {
3260
3261     $svc_acct->set_password($p->{'new_password'});
3262     my $error = $svc_acct->replace();
3263
3264     return { %$info, 'error' => $error } if $error;
3265
3266     #my($label, $value) = $svc_acct->cust_svc->label;
3267     #return { 'error' => $error,
3268     #         #'label' => $label,
3269     #         #'value' => $value,
3270     #       };
3271
3272   }
3273
3274   if ( $contact ) {
3275
3276     my $error = $contact->change_password($p->{'new_password'});
3277
3278     return { %$info, 'error' => $error }; # if $error;
3279
3280   }
3281
3282   #password changed ,so remove session, don't want it reused
3283   _cache->remove($p->{'session_id'});
3284
3285   return { %$info, 'error' => '' };
3286
3287 }
3288
3289 sub list_tickets {
3290   my $p = shift;
3291   my($context, $session, $custnum) = _custoragent_session_custnum($p);
3292   return { 'error' => $session } if $context eq 'error';
3293
3294   my @tickets = ();
3295   if ( $session->{'pkgnum'} ) { 
3296
3297     #tickets for specific service with pkg-balances on
3298     my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
3299                                           'pkgnum'  => $session->{'pkgnum'} })
3300                      or return { 'error' => 'unknown package' };
3301     foreach my $cust_svc ( $cust_pkg->cust_svc ) {
3302       push @tickets, $cust_svc->tickets( $p->{status} );
3303     }
3304
3305   } else {
3306
3307     my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
3308       or return { 'error' => "unknown custnum $custnum" };
3309
3310     @tickets = $cust_main->tickets( $p->{status} );
3311   }
3312
3313   # unavoidable false laziness w/ httemplate/view/cust_main/tickets.html
3314   if ( $FS::TicketSystem::system && FS::TicketSystem->selfservice_priority ) {
3315     my $conf = new FS::Conf;
3316     my $dir = $conf->exists('ticket_system-priority_reverse') ? -1 : 1;
3317     +{ tickets => [ 
3318          sort { 
3319            (
3320              ($a->{'_selfservice_priority'} eq '') <=>
3321              ($b->{'_selfservice_priority'} eq '')
3322            ) ||
3323            ( $dir * 
3324              ($b->{'_selfservice_priority'} <=> $a->{'_selfservice_priority'})
3325            )
3326          } @tickets
3327        ]
3328     };
3329   } else {
3330     +{ tickets => \@tickets };
3331   }
3332
3333 }
3334
3335 sub create_ticket {
3336   my $p = shift;
3337   my($context, $session, $custnum) = _custoragent_session_custnum($p);
3338   return { 'error' => $session } if $context eq 'error';
3339
3340   warn "$me create_ticket: initializing ticket system\n" if $DEBUG;
3341   FS::TicketSystem->init();
3342
3343   my $conf = new FS::Conf;
3344   my $queue = $p->{'queue'}
3345               || $conf->config('ticket_system-selfservice_queueid')
3346               || $conf->config('ticket_system-default_queueid');
3347
3348   warn "$me create_ticket: creating ticket\n" if $DEBUG;
3349   my $err_or_ticket = FS::TicketSystem->create_ticket(
3350     '', #create RT session based on FS CurrentUser (fs_selfservice)
3351     'queue'   => $queue,
3352     'custnum' => $custnum,
3353     'svcnum'  => $session->{'svcnum'},
3354     map { $_ => $p->{$_} } qw( requestor cc subject message mime_type )
3355   );
3356
3357   if ( ref($err_or_ticket) ) {
3358     warn "$me create_ticket: successful: ". $err_or_ticket->id. "\n"
3359       if $DEBUG;
3360     return { 'error'     => '',
3361              'ticket_id' => $err_or_ticket->id,
3362            };
3363   } else {
3364     warn "$me create_ticket: unsuccessful: $err_or_ticket\n"
3365       if $DEBUG;
3366     return { 'error' => $err_or_ticket };
3367   }
3368
3369
3370 }
3371
3372 sub did_report {
3373   my $p = shift;
3374   my($context, $session, $custnum) = _custoragent_session_custnum($p);
3375   return { 'error' => $session } if $context eq 'error';
3376  
3377   return { error => 'requested format not implemented' } 
3378     unless ($p->{'format'} eq 'csv' || $p->{'format'} eq 'xls');
3379
3380   my $conf = new FS::Conf;
3381   my $age_threshold = 0;
3382   $age_threshold = time() - $conf->config('selfservice-recent-did-age')
3383     if ($p->{'recentonly'} && $conf->exists('selfservice-recent-did-age'));
3384
3385   my $search = { 'custnum' => $custnum };
3386   $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
3387   my $cust_main = qsearchs('cust_main', $search )
3388     or return { 'error' => "unknown custnum $custnum" };
3389
3390 # does it make more sense to just run one sql query for this instead of all the
3391 # insanity below? would increase performance greately for large data sets?
3392   my @svc_phone = ();
3393   foreach my $cust_pkg ( $cust_main->ncancelled_pkgs ) {
3394         my @part_svc = $cust_pkg->part_svc;
3395         foreach my $part_svc ( @part_svc ) {
3396             if($part_svc->svcdb eq 'svc_phone'){
3397                 my @cust_pkg_svc = @{$part_svc->cust_pkg_svc};
3398                 foreach my $cust_pkg_svc ( @cust_pkg_svc ) {
3399                     push @svc_phone, $cust_pkg_svc->svc_x
3400                         if $cust_pkg_svc->date_inserted >= $age_threshold;
3401                 }
3402             }
3403         }
3404   }
3405
3406   my $csv;
3407   my $xls;
3408   my($xls_r,$xls_c) = (0,0);
3409   my $xls_workbook;
3410   my $content = '';
3411   my @fields = qw( countrycode phonenum pin sip_password phone_name );
3412   if($p->{'format'} eq 'csv') {
3413     $csv = new Text::CSV_XS { 'always_quote' => 1,
3414                                  'eol'          => "\n",
3415                                 };
3416     return { 'error' => 'Unable to create CSV' } unless $csv->combine(@fields);
3417     $content .= $csv->string;
3418   }
3419   elsif($p->{'format'} eq 'xls') {
3420     my $XLS1 = new IO::Scalar \$content;
3421     $xls_workbook = Spreadsheet::WriteExcel->new($XLS1) 
3422         or return { 'error' => "Error opening .xls file: $!" };
3423     $xls = $xls_workbook->add_worksheet('DIDs');
3424     foreach ( @fields ) {
3425         $xls->write(0,$xls_c++,$_);
3426     }
3427     $xls_r++;
3428   }
3429
3430   foreach my $svc_phone ( @svc_phone ) {
3431     my @cols = map { $svc_phone->$_ } @fields;
3432     if($p->{'format'} eq 'csv') {
3433         return { 'error' => 'Unable to create CSV' } 
3434             unless $csv->combine(@cols);
3435         $content .= $csv->string;
3436     }
3437     elsif($p->{'format'} eq 'xls') {
3438         $xls_c = 0;
3439         foreach ( @cols ) {
3440             $xls->write($xls_r,$xls_c++,$_);
3441         }
3442         $xls_r++;
3443     }
3444   }
3445
3446   $xls_workbook->close() if $p->{'format'} eq 'xls';
3447   
3448   { content => $content, format => $p->{'format'}, };
3449 }
3450
3451 sub get_ticket {
3452   my $p = shift;
3453   my($context, $session, $custnum) = _custoragent_session_custnum($p);
3454   return { 'error' => $session } if $context eq 'error';
3455
3456 #  warn "$me get_ticket: initializing ticket system\n" if $DEBUG;
3457 #  FS::TicketSystem->init();
3458 #  return { 'error' => 'get_ticket configuration error' }
3459 #    if $FS::TicketSystem::system ne 'RT_Internal';
3460
3461   # check existence and ownership as part of this
3462   warn "$me get_ticket: fetching ticket\n" if $DEBUG;
3463   my $rt_session = FS::TicketSystem->session('');
3464   my $Ticket = FS::TicketSystem->get_ticket_object(
3465     $rt_session, 
3466     ticket_id => $p->{'ticket_id'},
3467     custnum => $custnum
3468   );
3469   return { 'error' => 'ticket not found' } if !$Ticket;
3470
3471   if ( length( $p->{'subject'} || '' ) ) {
3472     # subject change
3473     if ( $p->{'subject'} ne $Ticket->Subject ) {
3474       my ($val, $msg) = $Ticket->SetSubject($p->{'subject'});
3475       return { 'error' => "unable to set subject: $msg" } if !$val;
3476     }
3477   }
3478
3479   if(length($p->{'reply'})) {
3480     my @err_or_res = FS::TicketSystem->correspond_ticket(
3481       $rt_session,
3482       'ticket_id' => $p->{'ticket_id'},
3483       'content' => $p->{'reply'},
3484     );
3485
3486     return { 'error' => 'unable to reply to ticket' } 
3487     unless ( $err_or_res[0] != 0 && defined $err_or_res[2] );
3488   }
3489
3490   warn "$me get_ticket: getting ticket history\n" if $DEBUG;
3491   my $err_or_ticket = FS::TicketSystem->get_ticket(
3492     $rt_session,
3493     'ticket_id' => $p->{'ticket_id'},
3494   );
3495
3496   if ( !ref($err_or_ticket) ) { # there is no way this should ever happen
3497     warn "$me get_ticket: unsuccessful: $err_or_ticket\n"
3498       if $DEBUG;
3499     return { 'error' => $err_or_ticket };
3500   }
3501
3502   my @custs = @{$err_or_ticket->{'custs'}};
3503   my @txns = @{$err_or_ticket->{'txns'}};
3504   my @filtered_txns;
3505
3506   # superseded by check in get_ticket_object
3507   #return { 'error' => 'invalid ticket requested' } 
3508   #unless grep($_ eq $custnum, @custs);
3509
3510   foreach my $txn ( @txns ) {
3511     push @filtered_txns, $txn 
3512     if ($txn->{'type'} eq 'EmailRecord' 
3513       || $txn->{'type'} eq 'Correspond'
3514       || $txn->{'type'} eq 'Create');
3515   }
3516
3517   warn "$me get_ticket: successful: \n"
3518   if $DEBUG;
3519   return { 'error'     => '',
3520     'transactions' => \@filtered_txns,
3521     'ticket_fields' => $err_or_ticket->{'fields'},
3522     'ticket_id' => $p->{'ticket_id'},
3523   };
3524 }
3525
3526 sub adjust_ticket_priority {
3527   my $p = shift;
3528   my($context, $session, $custnum) = _custoragent_session_custnum($p);
3529   return { 'error' => $session } if $context eq 'error';
3530
3531 #  warn "$me adjust_ticket_priority: initializing ticket system\n" if $DEBUG;
3532 #  FS::TicketSystem->init;
3533   my $ss_priority = FS::TicketSystem->selfservice_priority;
3534
3535   return { 'error' => 'adjust_ticket_priority configuration error' }
3536     if $FS::TicketSystem::system ne 'RT_Internal'
3537       or !$ss_priority;
3538
3539   my $values = $p->{'values'}; #hashref, id => priority value
3540   my %ticket_error;
3541
3542   foreach my $id (keys %$values) {
3543     warn "$me adjust_ticket_priority: fetching ticket $id\n" if $DEBUG;
3544     my $Ticket = FS::TicketSystem->get_ticket_object('',
3545       'ticket_id' => $id,
3546       'custnum'   => $custnum,
3547     );
3548     if ( !$Ticket ) {
3549       $ticket_error{$id} = 'ticket not found';
3550       next;
3551     }
3552     
3553   # RT API stuff--would we gain anything by wrapping this in FS::TicketSystem?
3554   # We're not going to implement it for RT_External.
3555     my $old_value = $Ticket->FirstCustomFieldValue($ss_priority);
3556     my $new_value = $values->{$id};
3557     next if $old_value eq $new_value;
3558
3559     warn "$me adjust_ticket_priority: updating ticket $id\n" if $DEBUG;
3560
3561     # AddCustomFieldValue works fine (replacing any existing value) if it's 
3562     # a single-valued custom field, which it should be.  If it's not, you're 
3563     # doing something wrong.
3564     my ($val, $msg);
3565     if ( length($new_value) ) {
3566       ($val, $msg) = $Ticket->AddCustomFieldValue( 
3567         Field => $ss_priority,
3568         Value => $new_value,
3569       );
3570     }
3571     else {
3572       ($val, $msg) = $Ticket->DeleteCustomFieldValue(
3573         Field => $ss_priority,
3574         Value => $old_value,
3575       );
3576     }
3577
3578     $ticket_error{$id} = $msg if !$val;
3579     warn "$me adjust_ticket_priority: $id: $msg\n" if $DEBUG and !$val;
3580   }
3581   return { 'error' => '',
3582            'ticket_error' => \%ticket_error,
3583            %{ customer_info($p) } # send updated customer info back
3584          }
3585 }
3586
3587 #--
3588
3589 sub _custoragent_session_custnum {
3590   my $p = shift;
3591
3592   my($context, $session, $custnum);
3593   if ( $p->{'session_id'} ) {
3594
3595     $context = 'customer';
3596     $session = _cache->get($p->{'session_id'})
3597       or return ( 'error' => "Can't resume session" ); #better error message
3598     $custnum = $session->{'custnum'};
3599
3600   } elsif ( $p->{'agent_session_id'} ) {
3601
3602     $context = 'agent';
3603     my $agent_cache = new FS::ClientAPI_SessionCache( {
3604       'namespace' => 'FS::ClientAPI::Agent',
3605     } );
3606     $session = $agent_cache->get($p->{'agent_session_id'})
3607       or return ( 'error' => "Can't resume session" ); #better error message
3608     $custnum = $p->{'custnum'};
3609
3610   } else {
3611     $context = 'error';
3612     return ( 'error' => "Can't resume session" ); #better error message
3613   }
3614
3615   ($context, $session, $custnum);
3616
3617 }
3618
3619 1;
3620