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