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