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