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