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