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