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