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