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