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