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