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