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